React项目出现'Uncaught (in promise) SyntaxError: Unexpected end of input'错误,求排查问题根源
Hey there, let's break down why you're hitting that SyntaxError: Unexpected end of input error in your React app and fix it up.
错误根源:mode: 'no-cors'的限制
When you added mode: 'no-cors' to your fetch options, you told the browser to make a request that blocks you from accessing the response content. This results in an "opaque response" — essentially, the browser gets the response but won't let your JavaScript code read any part of it.
So when you try to run codata.json(), there's no actual JSON data to parse (the response body is empty from your code's perspective), hence the "Unexpected end of input" error.
解决方案
Luckily, the ECDC COVID API you're using supports CORS (Cross-Origin Resource Sharing), so you don't need the no-cors mode at all. Here's how to fix your code:
- Remove the
mode: 'no-cors'option from your fetch call - Add a
try/catchblock to handle any other potential errors (like network issues)
Here's the updated code:
class App extends React.Component { gettingcovid = async (e) => { e.preventDefault(); try { const codata = await fetch('https://opendata.ecdc.europa.eu/covid19/casedistribution/json/'); const data = await codata.json(); console.log(data); } catch (error) { console.error('请求处理出错:', error); } } render() { return ( <div> <Covid /> <Form coviddata={this.gettingcovid} /> <Infected /> </div> ) } }
万一遇到不支持CORS的API怎么办?
If you ever need to call an API that doesn't support CORS, you'll need a workaround:
- Add a proxy in your React project: Add a
"proxy"field to yourpackage.jsonpointing to the API domain (e.g.,"proxy": "https://example.com"), then fetch from/covid19/casedistribution/json/instead of the full URL. - Use a backend service: Set up a simple backend server (Node.js, Python, etc.) that forwards your request to the target API — since server-side requests don't have CORS restrictions, you can then fetch from your own backend.
内容的提问来源于stack exchange,提问作者GrandpaHassan

