Express定义POST路由访问报Cannot GET错误问题求助
问题背景
编辑补充:我的实现目标是将新的
user添加到accounts数组中,感谢。
作为Express初学者,我正在学习基础HTTP请求用法,跟随Express路由教程练习,前期进展顺利,学到POST请求章节时遇到报错:Cannot GET /accounts/add-account,尝试了所有已知方案、搜索相关解决方法都没能解决,目前已经卡住。
以下是我写的实现代码:
const express = require('express'); const app = express(); const PORT = 3000; app.use(express.json()); app.listen(PORT, () => console.log(`Express server currently running on port ${PORT}`)); app.get('/', (request, response) => { response.json("Hello"); }); // 初始化账号数据 let accounts = [{ "id": 1, "name": "John Doe", "email": "fakeemail@emai.com", "password": "qw1212", }]; // 查询所有账号 app.get('/accounts', (request, response) => { response.json(accounts); }); // 按ID查询单个账号 app.get('/accounts/accountid/:id', (request, response) => { const accountId = Number(request.params.id); const getAccount = accounts.find((account) => account.id === accountId); if (!getAccount) { response.status(500).send('Account not found.') } else { response.json(getAccount); } }); // 新增账号接口 app.post('/accounts/add-account', (request, response) => { const newAccount = { "id": 2, "name": "Dohn Joe", "email": "realemail@emai.com", "password": "abc123", }; accounts.push(newAccount); response.json(accounts); })
报错原因
这个报错和你写的POST逻辑本身没关系,核心问题是HTTP方法不匹配:
你给/accounts/add-account路径注册的是POST方法的路由,但是直接在浏览器地址栏输入地址访问时,浏览器默认发送的是GET请求,Express服务端找不到对应路径的GET路由,就会返回Cannot GET /accounts/add-account的错误。
解决方案
- 正确测试POST接口:不要直接在浏览器地址栏访问这个路径,使用接口测试工具(Postman、Apifox、VS Code的Thunder Client插件,或者curl命令)向
http://localhost:3000/accounts/add-account发送POST请求,就能正常触发新增账号逻辑,返回更新后的完整账号列表。
用curl测试的命令参考:curl -X POST http://localhost:3000/accounts/add-account - 代码优化建议(非必须,但是更符合开发规范):
- 按ID查不到账号时,状态码应该用
404(资源不存在)而不是500(服务端内部错误) - 新增账号的ID不要写死固定值2,否则第三次新增账号就会出现ID重复,可以改成自动生成:
id: accounts.length ? accounts.at(-1).id + 1 : 1 - 正式场景下新增账号的参数应该从
request.body里取前端传过来的值,不要写死固定的账号信息
- 按ID查不到账号时,状态码应该用
内容的提问来源于stack exchange,提问作者PleaseDontHurtMe.jpeg
相关产品推荐
相关产品推荐

