javascript - 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;
};
解决方案
myEndpoint.js仅定义了一个GET
方法,但您的 axios 调用POST
在前端发送了一个。尝试更改(或添加)快速路线:
// notice the `.post`
router.post('/', authMiddleware, async function(req, res) {
...
})
由于这个原因,当您在浏览器中手动测试它时它也有效,因为浏览器发送了一个GET
请求。
推荐阅读
- java - 需要在java中反转循环
- php - 点击域名模式应该像弹出窗口一样打开
- css - 如何在 Alfresco 中更改 aikau-1.0.101.10.jar 中的 CSS 文件
- laravel - 如何从复选框选中的laravel设置值变量?
- scala - 在 scala 中写入 JDBC 源
- jquery - 如何在输入时触发输入文本中的事件?
- ios - swift:在执行另一个动作后调用动作
- asp.net-core - 即使 env.IsDevelopment 为真,Asp.Net Core 也不显示开发人员异常页面
- elasticsearch - Elasticsearch - 文本类型正则表达式
- python - Line Magics - PyCharm 中未解决的引用