node.js - 无法连接到 API 资源
问题描述
我创建了一个 React 前端,它向我的 api 发出 axios 发布请求。来自前端的代码在用户成功登录后被调用。用户登录成功后,通过 cookie 发送身份验证令牌,该 cookie 用于验证用户是否是管理员并且能够访问api 资源 /api/v1/orders。这在我在本地环境中时有效,但是在我将其上传到云端后,我收到此错误:
<MY_API>/api/v1/orders:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Adminpage.js:31 Error: Request failed with status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.p.onreadystatechange (xhr.js:62)
反应前端
管理页面.js
const loadOrders = async () => {
try {
const res = await axios.get(
"<MY_API>/api/v1/orders",
{
withCredentials: true,
}
);
console.log(res.data.data.orders);
setOrderData([...res.data.data.orders]);
} catch (err) {
console.log(err);
}
};
节点后端
orderRoutes.js
router
.route('/')
.get(
// Only admins can access this route
authController.requireSignin,
authController.isAdmin,
orderController.getAllOrders
)
.post(orderController.addOrder);
authController.js
exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
algorithms: ['HS256'], // added later
requestProperty: 'auth', // Decodes the token and assigns to auth object in request object
getToken: function (req) {
if (req.cookies.Authorization) {
return req.cookies.Authorization;
}
return null;
},
});
exports.isAdmin = (req, res, next) => {
// If users role specified in the req.auth object is not admin, an error is passed to the global error handler otherwise, is able to go to the next function
if (req.auth.role !== "admin") {
return next(
new ApiError(undefined, 403, "User is not authorized for access!")
);
}
next();
};
我的前端 React 代码托管在 AWS 上,我的后端 Nodejs 托管在 Azure 上。
解决方案
听起来像一个CORS问题。您是否在托管 API 的应用服务中启用了 CORS?https://github.com/uglide/azure-content/blob/master/articles/app-service-api/app-service-api-cors-consume-javascript.md
推荐阅读
- .net - 解码驾驶执照 PDF417 或磁条
- scala - sbt 找不到参数 valName 的隐式值
- java - 如何在android studio中处理双击事件onclicklistener?
- python-3.x - python3 错误 JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1,在 Ubuntu 中跳过解锁
- php - laravel 有什么方法可以在多对多关系中找到数据透视表中不存在的那些值?
- linux - 从多个文件中删除 c 样式的块注释
- javascript - 从角度传递时,Spring Boot 无法识别路径变量数据
- javascript - 如何增加/减少javascript中按钮的好恶?
- openssl - openssl s_client 没有密码匹配
- wordpress - 如何修复所有浏览器中的“TypeError:无法读取未定义的属性‘groupBy’”错误