无法请求/users/signup路由及数据库连接失败,注册功能异常求助
注册功能异常排查请求
- 无法向
/users/signup路由发送请求,数据库连接失败 - 登录功能在后端控制台有正常响应,但注册功能完全无法使用,其他功能与前端同步正常
相关代码及截图
1. 注册控制器代码
const signup = async (req, res) => { const { name, username, profilePhoto, email, password } = req.body; console.log(req.body); try { const existingUser = await User.findOne({ email }); if (existingUser) return res.status(404).json({ message: "User already exist." }); const hashedPassword = await bcrypt.hash(password, 12); const result = await User.create({ name, username, email, profilePhoto, password: hashedPassword, }); const token = jwt.sign( { name: result.name, email: result.email, username: result.username, id: result._id, }, "test", { expiresIn: "1h", } ); res.status(200).json({ result: result, token }); } catch (error) { res.status(500).json({ message: "Something went wrong" }); } };
2. 注册Action代码
export const signup = (formData, history) => async (dispatch) => { try { // sign up the user const { data } = await api.signUp(formData); dispatch({ type: "AUTH", data }); toast.success("Signed Up successfully"); history.push("/feedbacks"); } catch (error) { dispatch({ type: "ERROR", data: error?.response?.data }); toast.error(error?.response?.data?.message); } };
3. 错误截图

4. 控制台响应截图

5. 路由截图

6. 后端入口文件index.js代码
const express = require("express"); const connectDB = require("./config/db"); const cors = require("cors"); const app = express(); const feedbacksRoutes = require("./routes/feedbacks"); const userRoutes = require("./routes/users"); app.use(express.json({ extended: false })); app.use(cors()); // connect to mongoDB connectDB(); app.use("/feedbacks", feedbacksRoutes); app.use("/user", userRoutes);
排查方向
- 路由路径不匹配:后端入口挂载用户路由的路径是
/user,但前端请求的是/users/signup(注意单复数差异),会直接导致请求找不到对应路由返回404。 - 数据库连接问题:数据库连接失败会让注册时的
User.findOne、User.create操作抛出异常,进入catch块返回500错误,需先检查connectDB配置是否正确、数据库服务是否正常运行。 - 前端API路径错误:确认
api.signUp方法配置的请求URL是否和后端实际路由一致,是否因多写s导致路径不匹配。 - 错误信息优化:后端catch块可添加
console.log(error)打印具体错误,方便定位数据库或其他操作的具体问题,避免仅返回模糊的"Something went wrong"。
内容的提问来源于stack exchange,提问作者phoenix
相关产品推荐
相关产品推荐

