Express项目遇Cannot GET/ 404错误,寻求解决方案
Express 404 (Cannot GET /) 错误解决指南
问题描述
我编写了一段Express后端代码,但访问站点时出现Cannot GET /错误,同时控制台提示Failed to load resource: the server responded with a status of 404 (Not Found),尝试修复3天仍未解决,代码如下:
import express from 'express'; import jwt from 'jsonwebtoken'; import mongoose from "mongoose"; import { validationResult } from 'express-validator'; import { registerValidation } from "./validations/auth.js"; mongoose .connect('mongodb+srv://admin:wwwwww@cluster0.fjgxcgm.mongodb.net/?retryWrites=true&w=majority') .then(() => console.log('DB OK')) .catch((err ) => console.log('DB ERROR', err)); const app = express(); app.use(express.json()); app.post('/auth/register', registerValidation, (req, res ) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json(errors.array()); } res.json({ success: true, }); }); app.listen(4444, (err) => { if (err) { return console.log(err); } console.log('SERVER OK'); });
错误截图:
问题原因与解决方法
核心原因:你的代码只定义了
POST /auth/register这个接口,当直接访问根路径/时,Express找不到对应的路由处理逻辑,因此返回404错误。解决方法1:添加根路由处理
如果需要让根路径有正常响应,在app.use(express.json())之后添加一个GET路由:app.get('/', (req, res) => { res.send('服务器运行正常!'); // 也可以返回JSON格式:res.json({ status: 'ok', message: '服务器已启动' }); });解决方法2:访问正确的接口路径
如果你本来是要测试注册接口,不要直接访问http://localhost:4444/,而是通过POST请求访问http://localhost:4444/auth/register。可以用curl命令快速测试:curl -X POST -H "Content-Type: application/json" -d '{"email":"test@example.com","password":"123456"}' http://localhost:4444/auth/register或者用Postman、Insomnia等可视化工具发送POST请求,记得在请求体里传入符合
registerValidation校验规则的参数。可选:添加全局404处理中间件
为所有未定义的路由返回统一的404响应,在所有路由的最后添加:app.use((req, res) => { res.status(404).json({ code: 404, message: '请求的接口不存在' }); });
内容的提问来源于stack exchange,提问作者Yehor But
相关产品推荐
相关产品推荐

