[英]React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I want to fetch my Json file in react js, for this I am using fetch
.我想在 react js 中获取我的 Json 文件,为此我使用
fetch
。 But it shows an error但它显示一个错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
What could be the error, i am getting no clue.可能是什么错误,我不知道。 I even validated my JSON.
我什至验证了我的 JSON。
handleGetJson(){
console.log("inside handleGetJson");
fetch(`./fr.json`)
.then((response) => response.json())
.then((messages) => {console.log("messages");});
}
My Json (fr.json)我的 Json (fr.json)
{
"greeting1": "(fr)choose an emoticon",
"addPhoto1": "(fr)add photo",
"close1": "(fr)close"
}
Add two headers Content-Type
and Accept
to be equal to application/json
.添加两个标题
Content-Type
和Accept
以等于application/json
。
handleGetJson(){
console.log("inside handleGetJson");
fetch(`./fr.json`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((messages) => {console.log("messages");});
}
The solution that worked for me is that:- I moved my data.json file from src to public directory.对我有用的解决方案是:- 我将 data.json 文件从 src 移动到公共目录。 Then used fetch API to fetch the file.
然后使用 fetch API 来获取文件。
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL " http://localhost:3000/data.json " which is actually the public directory of my react app.问题是,在编译 react 应用程序后,获取请求会在 URL“ http://localhost:3000/data.json ”中查找文件,这实际上是我的 react 应用程序的公共目录。 But unfortunately while compiling react app data.json file is not moved from src to public directory.
但不幸的是,在编译 react app 时 data.json 文件没有从 src 移动到 public 目录。 So we have to explicitly move data.json file from src to public directory.
所以我们必须明确地将 data.json 文件从 src 移动到 public 目录。
This error can be received but be aware it can be a red herring to the real issue.可以接收到此错误,但请注意,它可能是对真正问题的一种红鲱鱼。 In my case, there wasn't an issue with the JSON as the error states, but rather a 404 was occurring that it could not pull the JSON data to process in the 1st place thus resulting in this error.
就我而言,错误状态下的 JSON 没有问题,而是发生了 404,它无法在第一个位置提取 JSON 数据进行处理,从而导致此错误。
The fix for this was that in order to use fetch
on a .json
file in a local project, the .json
file must be accessible.对此问题进行修复是为了使用
fetch
上.json
在本地项目文件中, .json
文件必须是可访问的。 This can be done by placing it in a folder such as the public
folder in the root of the project.这可以通过将它放在一个文件夹中来完成,例如项目根目录中的
public
文件夹。 Once I moved the json
file into that folder, the 404 turned into a 200, and the Unexpected token < in JSON at position 0
error was resolved.一旦我将
json
文件移动到该文件夹中,404 就变成了 200,并且Unexpected token < in JSON at position 0
的Unexpected token < in JSON at position 0
错误得到解决。
I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :我遇到了同样的错误,对我来说,这是因为 API 只是返回一个字符串,但是在 fetch 调用中我期待的是 json :
response => response.json()
Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do response.json()
从 API 返回 json 为我解决了这个问题,如果您的 API 不应该返回 json,那么就不要执行
response.json()
I had the same issue with fetch and decided to switch to axios.我对 fetch 有同样的问题,并决定切换到 axios。 Fixed the issue right away, here's the code snippet.
立即修复了问题,这是代码片段。
var axios = require('axios');
var config = {
method: 'get',
url: 'http://localhost:4000/'
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
I also had the same issue when trying to fetch the data from "/src" folder.尝试从“/src”文件夹中获取数据时,我也遇到了同样的问题。 Moving the file into the "/public" solved the problem from.
将文件移动到“/public”中解决了问题。
I had the same issue although I was requesting data from another web server and not locally.尽管我从另一个 Web 服务器而不是本地请求数据,但我遇到了同样的问题。 The response status code was 200 but I still didnt get the data, even though it was sent in JSON format by default.
响应状态码是 200 但我还是没有得到数据,即使它默认以 JSON 格式发送。 The (simple) problem was that I had forgot to include 'https://' in the url, so instead it used the local host in the beginning.
(简单的)问题是我忘记在 url 中包含“https://”,所以它在开始时使用了本地主机。
I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:我确认这里提出的一些方法也对我有用:您必须将本地 .json 文件放在 fetch() 正在查找的公共目录中(在 http://localhost:3000/ 中查找),例如:我使用这个fetch()在我的src/App.js文件中:
componentDidMount(){
fetch('./data/json-data.json')
.then ( resp1 => resp1.json() )
.then ( users1 => this.setState( {cards : users1} ) )
}
so I created public/data/json-data.json所以我创建了public/data/json-data.json
and everything was fine then :)然后一切都很好:)
It may come when the API(you are consuming) is not sending the corresponding JSON.当 API(您正在使用)未发送相应的 JSON 时,它可能会出现。 You may experience the response as 404 page or something like HTML/XML response.
您可能会遇到 404 页面或类似 HTML/XML 响应的响应。
on your Promise response you requested在您请求的 Promise 响应中
response.json()
but this works well if your server sends json response in return especially if you're using Node Js on the server side但是如果您的服务器发送 json 响应作为回报,这很有效,特别是如果您在服务器端使用 Node Js
So check again and make sure your server sends json as response as said if its NodeJS the response could be所以再次检查并确保您的服务器发送 json 作为响应,如果它的 NodeJS 响应可能是
res.json(YOUR-DATA-RESPONSE)
Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ...
, or <html><body>NOT FOUND</body></html>
).有时您的 API 后端无法遵守合同,并发送纯文本(即
Proxy error: Could not proxy request ...
,或<html><body>NOT FOUND</body></html>
)。
In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).在这种情况下,您需要处理两种情况:1) 有效的 json 响应错误,或 2) 作为回退的文本负载(当响应负载不是有效的 json 时)。
I would suggest this to handle both cases:我建议用这个来处理这两种情况:
// parse response as json, or else as txt
static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
(async () => {
var responseString = await response.text();
try{
if (responseString && typeof responseString === "string"){
var responseParsed = JSON.parse(responseString);
if (Api.debug) {
console.log("RESPONSE(Json)", responseParsed);
}
return jsonConsumer(responseParsed);
}
} catch(error) {
// text is not a valid json so we will consume as text
}
if (Api.debug) {
console.log("RESPONSE(Txt)", responseString);
}
return txtConsumer(responseString);
})();
}
then it become more easy to tune the rest handler:然后调整其余处理程序变得更加容易:
class Api {
static debug = true;
static contribute(entryToAdd) {
return new Promise((resolve, reject) => {
fetch('/api/contributions',
{ method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(entryToAdd) })
.catch(reject);
.then(response => Api.consumeResponseBodyAs(response,
(json) => {
if (!response.ok) {
// valid json: reject will use error.details or error.message or http status
reject((json && json.details) || (json && json.message) || response.status);
} else {
resolve(json);
}
},
(txt) => reject(txt)// not json: reject with text payload
)
);
});
}
I had the .json file in src folder.我在src文件夹中有 .json 文件。 Simply moved it in the public folder and it worked
只需将其移动到公共文件夹中即可
Try converting the response to string and then parse it to JSON.尝试将响应转换为字符串,然后将其解析为 JSON。 This solves the error for me.
这为我解决了错误。 Below is the code for the same.
下面是相同的代码。
let resp = JSON.stringify(response);
res = JSON.parse(resp);
I struggled with the same issue but then found a solution after doing some research.我在同样的问题上苦苦挣扎,但在做了一些研究后找到了解决方案。 The issue sometimes arises from a typing error.
该问题有时是由打字错误引起的。 Your console lets you know the type of error.
您的控制台让您知道错误的类型。
Here's is how I found out: In settings.py I wrote a double underscore: CORS__ORIGIN_ALLOW_ALL = True
instead of CORS_ORIGIN_ALLOW_ALL = True
.这是我的发现:在 settings.py 中,我写了一个双下划线:
CORS__ORIGIN_ALLOW_ALL = True
而不是CORS_ORIGIN_ALLOW_ALL = True
。
The issues persisted and I changed this 'the API Fetch method' and it worked just fine:问题仍然存在,我改变了这个“API Fetch 方法”,它工作得很好:
refreshList() {
fetch(process.env.REACT_APP_API+ "department")
.then((response) => response.json())
.then((data) => {
this.setState({ deps: data });
});
}
to:到:
refreshList() {
fetch("http://127.0.0.1:8000/" + "department")
.then((response) => response.json())
.then((data) => {
this.setState({ deps: data });
});
}
For me, I was making a call with fetch from a new computer and I forgot to add the env file to populate the process.env.REACT_APP_URL
and process.env.REACT_APP_API_KEY
fields.对我来说,我正在从一台新计算机上使用 fetch 进行调用,但我忘记添加 env 文件来填充
process.env.REACT_APP_URL
和process.env.REACT_APP_API_KEY
字段。 Adding back the .env file resolved the issue.添加回 .env 文件解决了这个问题。
I was getting the error.我收到了错误。 I simply added "proxy" in my package.json and the error went away.
我只是在 package.json 中添加了“代理”,错误就消失了。 The error was simply there because the API request was getting made at the same port as the react app was running.
错误只是在那里,因为 API 请求是在反应应用程序运行的同一端口上发出的。 You need to provide the proxy so that the API call is made to the port where your backend server is running.
您需要提供代理,以便对运行后端服务器的端口进行 API 调用。
Mostly this is caused with an issue in your React/Client app.这主要是由您的 React/Client 应用程序中的问题引起的。 Adding this line to your client
package.json
solves it将此行添加到您的客户端
package.json
解决
"proxy": " http://localhost:5000/ "
“代理”:“ http://localhost:5000/ ”
Note: Replace 5000, with the port number where your server is running注意:将 5000 替换为运行服务器的端口号
Reference: How to get create-react-app to work with a Node.js back-end API参考: 如何让 create-react-app 与 Node.js 后端 API 一起工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.