解析SyntaxError: Unexpected token < in JSON at position 0的问题
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
当你发送一个HTTP请求,可能是用Fetch或者其他的Ajax库,可能会出现这个错误提示,或者相似的错误。
接下来我将解释这是由什么引起的,我们应该怎样解决这些问题
1、引起的问题
这些错误发生在当你向服务器发送请求,返回值不是JSON而用JSON的方法解析的时候,发生这种情况的代码可能是这样的。
fetch('/users').then(response=> response.json())
请求数据没有问题,也许是res.json的问题
2. JSON.parse
用另一种方法JSON.parse
来解析Json的, 代码可能是这样的
JSON.parse(`不是Json的字符串`);
JSON.parse()
本质上是和res.json()
一样的,所以它们发生错误的情况是相同的。
3、解决方案
首先要做是先把返回值打印出来。如果用fetch,可以用res.text()
代替res.json()
来获得字符串。把你的代码转换成如下这样,并且通过打印出来的内容查看哪里出问题了。
fetch('/users')
// .then(res => res.json()) // comment this out for now
.then(res => res.text()) // convert to plain text
.then(text => console.log(text)) // then log it out
注意像res.json()
和res.text()
这样的方法是异步的。所以不能直接把它们的返回值打印出来,这就是console.log必须在.then的括号里面的原因。
是不是404页面?(可能是缺少该地址或者代码输入错误)。
这是不是index.html的页面?(可能是缺少地址或者代理配置错误)
如果一切看起来没问题(新加的地址,服务端没有重启),那就重启前端和后端服务器,看看是不是问题解决了




适用于现代 C++ 的 JSON。
最近提交(Master分支:6 个月前 )
c67d5382
* :alembic: try matrix for latest
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :recycle: refactor from https://github.com/nlohmann/json/issues/4745#issuecomment-2810128420
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix cpplint warning
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me> 1 天前
88c92e60
* :rotating_light: fix warnings
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix warnings
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :alembic: enable ranges support
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :fire: remove ci_nvhpc job
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :alembic: enable ranges support
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :fire: remove ci_nvhpc job
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix warning
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me> 2 天前
更多推荐
所有评论(0)