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

yftpprvb  于 2023-10-18  发布在  iOS
关注(0)|答案(3)|浏览(284)

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

  1. app.post('/post-login', urlencodeParser, async function (req, res) {
  2. const instance = axios.create();
  3. req.body.grant_type = "password";
  4. req.body.client_id = null;
  5. req.body.client_secret = null;
  6. const headers = {
  7. 'Content-Type': 'application/x-www-form-urlencoded'
  8. }
  9. try{
  10. const response = await instance.post(jsonData.baseURL+'/auth/login',JSON.stringify(req.body),{headers:headers});
  11. res.status(200).json(response);
  12. console.log(response);
  13. }catch(e){
  14. res.status(500).json({ message: e });
  15. }
  16. });

更新:
这是我在Postman

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

mccptt67

mccptt671#

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

  1. app.post('/post-login', urlencodeParser, async function (req, res) {
  2. const instance = axios.create();
  3. req.body.grant_type = "password";
  4. req.body.client_id = null;
  5. req.body.client_secret = null;
  6. const headers = {
  7. 'Content-Type': 'application/x-www-form-urlencoded'
  8. }
  9. try{
  10. const response = await instance.post(jsonData.baseURL+'/auth/login', req.body,{headers:headers});
  11. res.status(200).json(response);
  12. console.log(response);
  13. }catch(e){
  14. res.status(500).json({ message: e });
  15. }
  16. });

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

展开查看全部
klr1opcd

klr1opcd2#

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

  1. import axios from 'axios';
  2. const dataAPI = axios.create();
  3. 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的情况下,头将不会与请求一起沿着。
非工作样品:

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

工作样品:

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

相关问题