api - Express API 发布请求中出现 401 未经授权的错误
问题描述
我正在尝试为 Express 中的 POST 路由处理程序开发逻辑。我将以下内容放在一起:
const headers = {
"Authorization":"TS Token asdfghjk-asdf-4567-fghjkl; tid=onfido-token";
"content-type": "application/json"
};
const params = {
"policy_request_id": "onfido_applicantandtoken"
};
app.get("/get_stuff", (req, res) => {
axios
.post("https://third/party/api", {
headers,
params
})
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
res.json("Error occured!");
});
}
});
对于上述情况,我不断收到 401 Unauthorized。在 Postman 上它可以工作,但是根据上面的逻辑,我得到 401 Unauthorized,特别是在我会得到的日志中Header 'Authorization' not found
或Could not parse authorization header
. 所以我不清楚标题会发生什么。
很多帖子都在谈论req.headers
,但我req.headers
没有授权令牌和内容类型,它有一些其他令牌,我试图连接的 API 我认为需要联系另一个 API。
我已将其重构为如下所示:
app.get("/get_stuff", (req, res) => {
axios
.post("https://third/party/api", params, headers)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
res.json("Error occured!");
});
}
});
而且我仍然遇到同样的错误。
需要明确的是,参数不是传递到 Postman 上的 URL 的东西,而是邮递员请求的正文。
解决方案
通过像这样声明全局 axios 默认值,我能够使其成功连接:
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
如此处所述:
https://www.npmjs.com/package/axios#user-content-config-defaults
推荐阅读
- reactjs - 输入值清除 - React Hooks
- jenkins - 如何使用自定义提交消息设置 web-hook?
- r - 包括出现值的所有行,否则,删除
- java - 如何使用 maven 构建 Javafx + Spring 进行生产
- mysql - 具有多个 AND OR 条件的原则
- java - 数组 B 中数组 A 中对象的访问方法
- php - 无法使用正确的用户名和密码登录php和myql
- android - Android 项目无法解析 org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50
- python - 这是什么意思?为什么需要它?cur_row, cur_col = cur_path[-1]
- docker - 如何使用 Docker 和 DigitalOcean Spaces 部署 TensorFlow Serving