Axios:在进行POST请求时返回404

yftpprvb  于 12个月前  发布在  iOS
关注(0)|答案(3)|浏览(231)

我是nodejs和axios的新手。我正在努力使登录工作的时刻,但Axios是给我一个404 not found错误,每当我调用它在我的控制器。
我就是这么做的。我很确定我正确地使用了axios。我不知道为什么会出现404错误。

app.post('/post-login', urlencodeParser, async function (req, res) {
    const instance = axios.create();
    req.body.grant_type = "password";
    req.body.client_id = null;
    req.body.client_secret = null;
    
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    try{
      const response = await instance.post(jsonData.baseURL+'/auth/login',JSON.stringify(req.body),{headers:headers});
      res.status(200).json(response);
      console.log(response);
    }catch(e){
      res.status(500).json({ message: e });
    }
});

更新:
这是我在Postman

中测试API端点时得到的结果
这是标题

mccptt67

mccptt671#

我认为问题可能是你使用了json编码的数据(通过使用json.stringify),并使用'application/x-www-form-urlencoded'内容类型发送它。我建议你不要编码尸体。就像这样:

app.post('/post-login', urlencodeParser, async function (req, res) {
    const instance = axios.create();
    req.body.grant_type = "password";
    req.body.client_id = null;
    req.body.client_secret = null;
    
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    try{
      const response = await instance.post(jsonData.baseURL+'/auth/login', req.body,{headers:headers});
      res.status(200).json(response);
      console.log(response);
    }catch(e){
      res.status(500).json({ message: e });
    }
});

More on why you should not pass an encoded json to axis with form content-type

klr1opcd

klr1opcd2#

对于像我这样来自搜索引擎的人来说,如果你使用单例模式来访问axios示例,即:

import axios from 'axios';

const dataAPI = axios.create();

export default dataAPI;

确保您的Axios示例没有被axios-mock-adapter修改。如果是,调用adapter.restore()返回初始状态。
注意:.restore().reset()之间存在差异
引用文档
您可以恢复原始适配器(这将移除模仿行为)
mock.restore();
还可以使用resetHandlers重置已注册的模拟处理程序
mock.resetHandlers();
您可以使用reset重置已注册的模拟处理程序和历史项
mock.reset();

pb3s4cty

pb3s4cty3#

对于Typescript的人谁达到了这个问题从搜索引擎:
确保将http标头值框在引号中。
Node的HTTPS请求将接受不带引号的boolean和numbers的header,但axios只接受带引号的值。因此,如果我们在axios中使用与https/http相同的头,那么在axios的情况下,头将不会与请求一起沿着。
非工作样品:

const config = {
        headers: {'x-mock-match-request-body':false, 'x-mock-match-request-headers':false}
      };
      const response = await axios.post(requestUrl, null, config);

工作样品:

const config = {
        headers: {'x-mock-match-request-body':'false', 'x-mock-match-request-headers':'false'}
      };
      const response = await axios.post(requestUrl, null, config);

相关问题