React订阅组件报错Unhandled Rejection (SyntaxError):Unexpected end of input求解
Fixing Your React Email Subscription Component Error
Hey Ricardo, let's break down why you're seeing that Unexpected end of input error and get your subscription feature working properly. Here's what's going wrong and how to fix it:
Key Issues in Your Current Code
mode: 'no-cors'blocks response parsing: When you use this mode, the browser restricts access to the response content. Callingresponse.json()will fail because the response is "opaque"—you can't read its body at all.- Incorrect request format for the Mailchimp API: The list-manage endpoint you're using expects data in
application/x-www-form-urlencodedformat (not JSON), and the email parameter must be namedEMAIL(not theemailyou're using). - Flawed email validation:
if (this.state.email > 3)is a broken check—you're comparing a string to a number, which won't properly validate if the email is valid or even non-empty.
Corrected Component Code
import React from "react"; class SubscribeOffer extends React.Component { constructor() { super(); this.state = { email: "" }; } fillEmailToSubscribe = (event) => { this.setState({ email: event.target.value }); }; // Helper to validate proper email format isValidEmail = (email) => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }; submitEmailToSubscribe = () => { const { email } = this.state; // Validate email first before sending request if (!this.isValidEmail(email)) { alert("Please enter a valid email address!"); return; } // Encode data in the format Mailchimp expects const formData = new URLSearchParams(); formData.append("EMAIL", email); // Add any other required fields from your Mailchimp list here (like FNAME if you've set it up) fetch('https://(myuser).list-manage.com/subscribe/post?u=(somenumber)&id=(myid)', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData.toString(), }) .then((response) => { // Check if the request was successful if (response.ok) { alert('Thank you for subscribing!'); this.setState({ email: "" }); // Clear input after successful subscription } else { alert('Oops, something went wrong. Please try again later.'); } }) .catch((error) => { console.error('Subscription error:', error); alert('Oops, something went wrong. Please try again later.'); }); }; render() { return ( <div> <h1>Get updated upcoming events in your inbox everyday!</h1> <p>Would you like us to send you updates about future events?</p> <input type='email' name='email-address' id='email-address' placeholder="your email" onChange={this.fillEmailToSubscribe} value={this.state.email} required /> <button onClick={this.submitEmailToSubscribe}>Subscribe</button> </div> ); } } export default SubscribeOffer;
What Changed & Why
- Removed
mode: 'no-cors': This lets us read the API response properly. If you hit CORS issues later, you'll need to use a proxy server or confirm your Mailchimp list is configured to accept requests from your domain. - Switched to
application/x-www-form-urlencoded: Mailchimp's subscription endpoint requires this format, so we useURLSearchParamsto encode the data correctly and set the matching header. - Added proper email validation: The
isValidEmailhelper uses a regex to check for a valid email structure, which is way more reliable than a length-based check. - Improved error handling: We now catch fetch errors and check the response status, so we can show meaningful alerts instead of letting the error go unhandled.
- Made the input a controlled component: Added
value={this.state.email}to ensure the input always matches the component's state.
Extra Tips
- Don't forget to replace
(myuser),(somenumber), and(myid)in the fetch URL with your actual Mailchimp list details. - If you still run into CORS problems, consider setting up a simple proxy server (like using
http-proxy-middlewarewith Create React App) to forward requests to the Mailchimp endpoint.
内容的提问来源于stack exchange,提问作者Ricardo Sawir
相关产品推荐
相关产品推荐

