javascript - UnhandledPromiseRejectionWarning:来自 Node JS 的未处理的承诺拒绝,React 中的预检响应
问题描述
在反应 JS 中:
这是我的代码:
....some code......
verifyTokenResults = await axios.post('http://localhost:5000/otp/token/verify', {accessToken: authToken})
上面,我通过 request.body 将一个令牌从 React 发布到下面的 Node JS 路由:
这是我在 Node JS / Express JS 中的端点:
router.post('/token/verify', async (request, response) =>{
const tokenToVerify = request.body.accessToken;
console.log(tokenToVerify);
let cachedToken;
let individualAccessToken;
let emailWithToken;
if (tokenToVerify) {
cachedToken = await accessTokenModel.find({accessToken: tokenToVerify}).sort({_id: -1}).limit(1);
//access the accessToken key of the returned json
for (let record of cachedToken) {
individualAccessToken = record["accessToken"];
emailWithToken = record["email"];
}
if (individualAccessToken === tokenToVerify) {
return response.status(200).json({message: `JWT Token Verified Successfully!`});
} else {
return response.status(404).json({message: `Invalid JWT Token!`});
}
}
});
**这是我在使用 try...catch 包装我的方法之前在 Node JS 控制台中遇到的错误:
我收到以下错误:**
(node:2252) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'accessToken' of undefined
(node:2252) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
当我用 try...catch 包装函数时,In React 在完成请求后不会继续前进。它给了我一个预检
解决方案
我假设您使用的是 Express。
为了快速处理 JSON 发布数据,您必须express.json()
在应用程序上使用中间件。中间件解析 JSON,并将其转换为原生 js 对象,将其绑定到request.body
.
然后,您可以像这样访问 JSON 的内容:
const tokenToVerify = request.body.accessToken
旁注:在服务器端存储 JWT 完全违背了 JWT 的目的,即消除存储会话数据的需要。
相反,JWT 应该存储在客户端 localStorage 中。然后,在后续请求中,客户端在请求的授权标头中设置其访问令牌。
您还可以将 JWT 设置为 httpOnly cookie,访问令牌将与后续请求一起发送。
推荐阅读
- java - Java Spring Thymeleaf 下拉菜单被禁用并出现
- excel - Vlookup 返回的事件编号在单个单元格中与 ROW () 分组
- node.js - 为什么部署的无服务器函数未显示在 AWS 控制台的 lambda 函数列表中?
- c++ - 如何在 Visual Studio 中仅禁用系统文件(msvc、windows kits)的智能感知?
- java - 我的 Rent 数组中的 LocalDate 要求我将其转换为字符串
- javascript - 当我们移动到角度 6 中的另一个组件时,如何销毁一个组件?
- codeigniter - 交易方式如何正确?
- regex - Golang中正则表达式中的斜线
- java - 如何从列表中迭代值
在电子表格控件的 GridBase 的 setCellValue 方法中? - javascript - 用 JavaScript 做了一个关于我自己的测验