javascript - 如果Server以text/html类型响应,Client会识别不出来吗?
问题描述
我尝试使用 localStorage.removeItem() 函数擦除 jwt 令牌,但由于运行下面的代码而失败。
我在 Visual Studio Code 中使用 Javascript 和 Express.js 进行编码。并使用 Chrome 浏览器。
[客户]
secession = () => {
fetch('http://localhost:3000/users/secession', {
headers: {
'Content-Type': 'application/json',
'accessToken': JSON.stringify(localStorage.getItem('tokenValue')),
}
})
.then((result) => {
return result.json();
})
.then((data) => {
if (data === 'success secession') {
localStorage.removeItem('tokenValue');
alert('Success');
} else {
alert('Fail. Try again');
}
})
.catch((err) => err);
}
[服务器]
secession: async (req, res) => {
try {
const token = req.get('accessToken');
if (typeof token !== 'undefined') {
const decoded = jwt.verify(JSON.parse(token), secretKey);
const result = await users.users.secession(decoded);
// result is 'success secession'
res.send(result);
} else {
res.sendStatus(403);
}
} catch (err) {
res.send(err);
}
}
当我在服务器上将res.send(result)更改为res.json(result)时,我成功擦除了令牌。
我认为如果服务器通过 text/html发送结果,客户端不会收到响应。
但我不确定这是否正确。
解决方案
您正在向客户端发送非 JSON 的内容。有了这条线:
return result.json();
您告诉浏览器将其解析为 JSON。它不是。但是,使用以下行将引发异常:
.catch((err) => err);
你正在吞噬所有的错误。抛出它是有原因的:您正在为.json
函数提供无效输入。
删除.json
解析器。您可以将其替换为.text()
.
背景资料:
使用res.json()
“修复”问题的原因是因为运行JSON.stringify
会some "string" value
导致"some \"string\" value"
,这是有效的 JSON。JSON 对象可能只是一个字符串,它不必是对象或数组。
推荐阅读
- php - PDFLib 表 PHP
- android-source - 如果我们将 SELinux 设置为 Permissive 模式会发生什么
- javascript - AFrame+Three.js 在每个有几个三角形的多个网格和每个有很多三角形的几个网格之间有什么更高的性能?
- php - 当我输入 IP 地址作为 URL 时,WordPress 没有加载,我只得到默认的 Ubuntu 页面(Ubuntu 18.04)
- python - 除了执行 dry_run FCM 发送之外,验证 Firebase 令牌 ID 的可靠方法是什么?
- node.js - 使用 sequelize 模型获取计算字段
- java - 如何配置/创建自定义类路径,这对于码头中的许多 Web 应用程序中的少数几个是通用的
- java - 需要使用 Java / Selenium 或任何语言从 Googe TAG 管理器中提取数据层信息 - 用于自动化目的
- dns - 使用 BIND 9 拆分域
- r - 在 R 中使用循环创建 wordcloud 输出