首页 > 解决方案 > Axios 发布请求失败并出现 404

问题描述

我正在使用 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;
};

获取我的端点属性

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;
};

标签: javascriptnode.jsexpressvue.jsaxios

解决方案


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

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

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


推荐阅读