繁体   English   中英

Express API 发布请求中出现 401 未经授权的错误

[英]401 Unauthorized error in Express API post request

我正在尝试为 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 所以我不清楚 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 的东西,而是 postman 请求的主体。

通过声明全局 axios 默认值,我能够使其成功连接,如下所示:

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

如此处所述:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM