React JS:未捕获(在承诺中)语法错误:在位置 0 的 JSON 中意外<令牌
React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
我想在 react js 中获取我的 Json 文件,为此我正在使用 fetch
.但它显示错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
可能是什么错误,我没有任何线索。我什至验证了我的 JSON。
handleGetJson(){
console.log("inside handleGetJson");
fetch(`./fr.json`)
.then((response) => response.json())
.then((messages) => {console.log("messages");});
}
My Json (fr.json(
{
"greeting1": "(fr)choose an emoticon",
"addPhoto1": "(fr)add photo",
"close1": "(fr)close"
}
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");});
}
对我有用的解决方案是:-我将我的 data.json 文件从 src 移动到公共目录。然后使用获取 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);
});
问题是在编译 react 应用程序后,获取请求在 URL "http://localhost:3000/data.json" 处查找文件,这实际上是我的 react 应用程序的公共目录。但不幸的是,在编译反应应用程序时,data.json 文件没有从 src 移动到公共目录。所以我们必须显式地将 data.json 文件从 src 移动到公共目录。
可以收到此错误,但请注意,这可能是真正问题的红鲱鱼。就我而言,JSON没有错误状态的问题,而是发生了404,它无法首先提取JSON数据进行处理,从而导致此错误。
解决此问题的解决方法是,为了在本地项目中的.json
文件上使用fetch
,.json
文件必须是可访问的。这可以通过将它放在项目根目录中的文件夹(如public
文件夹(来完成。一旦我将json
文件移动到该文件夹中,404就变成了200,并且Unexpected token < in JSON at position 0
错误得到了解决。
我遇到了同样的错误,对我来说,这是因为 API 只是返回一个字符串,但是在获取调用中我期待 json:
response => response.json()
从 API 返回 json 为我解决了这个问题,如果您的 API 不应该返回 json,那么就不要这样做response.json()
尝试从"/src"文件夹获取数据时,我也遇到了同样的问题。将文件移动到"/public"中为我解决了问题。
我在获取时遇到了同样的问题,并决定切换到 axios。立即修复了问题,这是代码片段。
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);
});
我从另一个 Web 服务器而不是本地请求数据,但我遇到了同样的问题。响应状态代码为 200,但我仍然没有收到数据,即使默认情况下它是以 JSON 格式发送的。(简单的(问题是我忘记在 url 中包含"https://",所以它在开始时使用了本地主机。
我确认这里提出的一些方法也对我有用:您必须将本地.json文件放在fetch((正在寻找的公共目录中(在 http://localhost:3000/中查找(例如:我在我的 src/App.js 文件中使用此 fetch((:
componentDidMount(){
fetch('./data/json-data.json')
.then ( resp1 => resp1.json() )
.then ( users1 => this.setState( {cards : users1} ) )
}
所以我创建了public/data/json-data.json
一切都很好,然后:)
在你的承诺响应上您请求
response.json()
但是如果您的服务器发送 JSON 响应作为回报,这很有效特别是如果你在服务器端使用 Node Js
因此,请再次检查并确保您的服务器发送 json 作为响应如前所述,如果它的 NodeJS 响应可能是
res.json(YOUR-DATA-RESPONSE)
有时您的API后端无法遵守合同,并发送纯文本(即。 Proxy error: Could not proxy request ...
或<html><body>NOT FOUND</body></html>
(。
在这种情况下,您需要处理这两种情况:1( 有效的 json 响应错误,或 2( 文本有效负载作为回退(当响应有效负载不是有效的 json 时(。
我建议这样做来处理这两种情况:
// 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);
})();
}
然后,调整 REST 处理程序变得更加容易:
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
)
);
});
}
尝试将响应转换为字符串,然后将其解析为 JSON。这为我解决了错误。下面是相同的代码。
let resp = JSON.stringify(response);
res = JSON.parse(resp);
当 API(您正在使用(未发送相应的 JSON 时,可能会出现这种情况。您可能会遇到 404 页面或类似 HTML/XML 响应的响应。
我在src文件夹中有.json文件。只需将其移动到公共文件夹中即可工作
我在同样的问题上挣扎,但在做了一些研究后找到了解决方案。该问题有时由键入错误引起。您的主机会让您知道错误类型。
以下是我发现的方式:settings.py 年我写了一个双下划线:CORS__ORIGIN_ALLOW_ALL = True
而不是 CORS_ORIGIN_ALLOW_ALL = True
.
问题仍然存在,我更改了这个"API 获取方法",它工作得很好:
refreshList() {
fetch(process.env.REACT_APP_API+ "department")
.then((response) => response.json())
.then((data) => {
this.setState({ deps: data });
});
}
自:
refreshList() {
fetch("http://127.0.0.1:8000/" + "department")
.then((response) => response.json())
.then((data) => {
this.setState({ deps: data });
});
}
,我正在用从新计算机获取进行调用,但我忘记添加 env 文件来填充process.env.REACT_APP_URL
和process.env.REACT_APP_API_KEY
字段。重新添加 .env 文件解决了该问题。
添加"method: 'GET'">
let query = {
method: 'GET',
headers: {
authToken: token,
"Content-Type": "application/json",
},
};
with datas in public/datas/datas.json :
export default class App extends React.Component {
constructor(props) {
super(props);
}
async componentDidMount() {
const response = await fetch("datas/datas.json");
const datas = await response.json();
console.log(datas);
}
...
首先,在顶部添加下面给出的代码行:
const port = process.env.PORT || 3000;
确保您的fr.json
在公用文件夹中。然后编写如下代码:
fetch(`http://localhost:${port}/fr.json`)
.then((response) => response.json())
.then((messages) => {console.log("messages");});
我得到了错误。我只是在我的package.json中添加了"代理",错误就消失了。错误只是因为 API 请求是在 react 应用程序运行的同一端口发出的。您需要提供代理,以便对运行后端服务器的端口进行 API 调用。
大多数情况下,这是由 React/Client 应用程序中的问题引起的。 将此行添加到客户端package.json
解决它
"代理":"http://localhost:5000/">
注意:将 5000 替换为运行服务器的端口号
参考:如何让 create-react-app 使用 Node.js 后端 API
- React JS:未捕获(在承诺中)语法错误:在位置 0 的 JSON 中意外<令牌
- 当其他解析器认为意外的令牌有效时,json.parse会失败
- 如何在核心php应用程序中使用节点js json Web令牌库
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- JSON 中位置 4 处的意外令牌<
- “JSON.parse(str)”返回“意外令牌c”,但str是一个字符串
- Javascript JSON.parse:未捕获的语法错误:意外的令牌N
- 为什么JSON.parse()在尝试解析一个简单的JSON对象时抛出Uncaught SyntaxError:意外的令牌
- 反伪造令牌和Ajax JSON.stringify Post不起作用
- 意外的令牌:用于Javascript中的JSON字符串
- 试图解析一个大型JSON对象并提取数据,但不断出现意外的令牌错误
- JSON.parse引发意外的令牌错误
- 解析有效的 JSON 得到“语法错误:意外令牌非法”
- 尝试用 JSON 编写函数,在函数调用中获取“意外令牌”
- JSON 解析:未捕获语法错误:意外令牌 e
- JSON 语法错误:意外的令牌<
- JSON 语法错误:未捕获语法错误:意外令牌 [.
- JSON 解析:未捕获的语法错误:意外的令牌,JavaScript
- 跨 ajax 请求到服务器返回的 json 对象显示错误意外令牌:
- 如何将.json文件上传到谷歌云端硬盘,使用谷歌JavaScript库(gapi)和访问令牌