首页 > 解决方案 > 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 foundCould 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 的东西,而是邮递员请求的正文。

标签: apiexpresspostaxios

解决方案


通过像这样声明全局 axios 默认值,我能够使其成功连接:

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

如此处所述:

https://www.npmjs.com/package/axios#user-content-config-defaults


推荐阅读