【问题标题】:Axios post request failing with a 404Axios 发布请求失败并出现 404
【发布时间】:2021-03-10 03:18:55
【问题描述】:

我正在使用 Axios 在我的后端查询一个端点。当我尝试这样做时,我得到一个 404 not found 。如果我从控制台复制/粘贴它在错误中给出的 uri 并尝试直接在浏览器中访问它,它连接正常并且不会给我一个错误(而是给我一个预期的空对象)。

下面是我的 Axios 代码

axios.post("/api/myEndpoint", { id: this.userID })
      .then((response) => { 
        this.property = response.data.property;
      })
      .catch((errors) => {    
        console.log(errors);    
        router.push("/");    
      });

下面是我后端的路由定义

const myEndpointRoute = require('../api/myEndpoint.js')();
exprApp.use('/api/myEndpoint', myEndpointRoute);

作为参考,URI 是“http://localhost:3000/api/myEndpoint”。我可以在浏览器中完全访问这个 uri,但 Axios 会返回 404,如上所述。正是出于这个原因,我确信这是前端的一个问题,但是我已经以与我拥有的许多其他请求相同的方式设置了这个 Axios 请求,并且它们都可以正常工作。

编辑:这是后端的其余部分

myEndpoint.js

module.exports = function() {
const express = require('express'), router = express.Router();
const authMiddleware = require('../loaders/authMiddleware.js')();

router.get('/', authMiddleware, async function(req, res) {
  const id = req.body.id;

  const property = await require('../services/myEndpointService.js') 
    (id).catch((e) => { console.log(e) });
    res.send({ property: property });
  });

  return router;
};

myEndpointService.js

module.exports = async function(id) {
  const results = await require('../models/getMyEndpointProperty')(id);

  return results;
};

getMyEndpointProperty

module.exports = async function(id) {
  const pool = require('../loaders/pool.js')();

  const res = await pool.query(`SELECT * FROM myTable WHERE id = ${id};`);
  return res.rows;
};

【问题讨论】:

  • 你能显示 myEndpoint.js 吗?
  • 我添加了一些额外的后端信息

标签: javascript node.js express vue.js axios


【解决方案1】:

myEndpoint.js 仅定义了一个 GET 方法,但您的 axios 调用在前端发送了一个 POST。尝试更改(或添加)快速路线:

// notice the `.post`
router.post('/', authMiddleware, async function(req, res) {
...
})

由于这个原因,当您在浏览器中手动测试它时它也可以工作,因为浏览器发送了一个GET 请求。

【讨论】:

  • 谢谢你,我一定是看了 1000 遍那个文件并没有注意到
猜你喜欢
  • 2019-02-25
  • 2018-10-17
  • 2018-05-28
  • 2022-11-13
  • 2021-05-18
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多