React向数据库提交数据时遭遇404(Not Found)错误求助
问题分析与解决方案
核心问题:404 Not Found
你遇到的POST http://localhost:3000/topic/create 404错误,本质是请求地址不存在,和useDispatch的使用无关。主要原因有两个:
1. 修复前端API请求地址配置
你的RTK Query apiSlice没有指定后端服务的baseURL,导致请求默认发送到前端所在的localhost:3000端口,而前端并没有/topic/create这个路由。
解决方法:
在创建apiSlice时明确设置后端地址(假设后端运行在localhost:5000):
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; export const apiSlice = createApi({ baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:5000' }), // 这里改为你的后端端口 endpoints: () => ({}), });
2. 确保后端存在对应路由
检查你的Express后端是否配置了POST /topic/create的路由,并且正确处理MongoDB数据存储。
示例后端路由代码:
const express = require('express'); const router = express.Router(); const Topic = require('../models/Topic'); // 你的MongoDB Topic模型 const cors = require('cors'); router.use(cors()); // 允许跨域请求 router.post('/create', async (req, res) => { try { const { title, author } = req.body; const newTopic = new Topic({ title, author }); await newTopic.save(); res.status(201).json(newTopic); } catch (err) { res.status(400).json({ error: err.message }); } }); module.exports = router; // 在app.js中挂载路由 app.use('/topic', router);
3. 移除无效的dispatch代码
你的submitHandler中dispatch({ ...res })完全无效:RTK Query的mutation会自动处理请求流程,返回的res是后端数据,不是Redux action,不需要手动dispatch。直接删除这行代码即可:
const submitHandler = async (e) => { e.preventDefault(); try { await create({ title, author: userInfo.name }).unwrap(); // 直接用userInfo.name,无需单独维护state navigate("/"); } catch (err) { toast.error(err.error); } };
4. 优化表单author字段
你不需要单独维护author状态,直接使用userInfo.name即可,还可以设置输入框为禁用状态避免修改:
// 移除const [author, setAuthor] = useState(""); // 表单中的author控件修改为: <Form.Group className="my-2" controlId="author"> <Form.Label>Author</Form.Label> <Form.Control type="text" value={userInfo.name} disabled ></Form.Control> </Form.Group>
内容的提问来源于stack exchange,提问作者Dagger
相关产品推荐
相关产品推荐

