MERN Stack API URL请求失败,Redux报404错误求助
解决Redux请求404错误:排查与修复方案
问题概述
触发getAllPizzas Redux Action后,控制台返回404错误,无法获取披萨数据。已检查路由与URL路径,但未定位到问题,相关代码如下:
Action代码
import axios from 'axios' export const getAllPizzas = () => async (dispatch) => { dispatch({ type: 'GET_PIZZAS_REQUEST' }) try { const response = await axios.get('/api/pizzas/getallpizzas') console.log(response) dispatch({ type: 'GET_PIZZAS_SUCCESS', payload: response.data }) } catch (error) { dispatch({ type: 'GET_PIZZAS_FAILED', payload: error }) } }
Reducer代码
export const getAllPizzasReducer = (state = { pizzas: [] }, action) => { switch (action.type) { case 'GET_PIZZAS_REQUEST': return { loading: true, ...state } case 'GET_PIZZAS_SUCCESS': return { laoding: false, pizzas: action.payload } case 'GET_PIZZAS_FAILED': return { error: action.payload, loading: false } default: return state } }
路由文件代码
const express = require('express') const router = express.Router() const Pizza = require('../models/pizzaModel') router.get('/getallpizzas', async (req, res) => { try { const pizzas = await Pizza.find({}) res.send(pizzas) } catch (error) { return res.status(400).json({ message: error }) } }) module.exports = router
服务器文件代码
const express = require('express') const Pizza = require('./models/pizzaModel') const app = express() require('dotenv').config() const db = require('./db') app.use(express.json()) const pizzasRoute = require('./routes/pizzasRoute') app.use('/api/pizzas/', pizzasRoute) app.get('/', (req, res) => { res.send(`Server Working nice :), Your port being ${port}`) }) const port = process.env.PORT || 5000 app.listen(port, () => { console.log(`Server is running on port ${port}`) })
问题排查与修复
1. 后端服务器变量引用顺序错误
服务器文件中,根路由app.get('/')在port变量定义前就使用了${port},会导致port为undefined,可能引发服务器启动异常或响应错误。
修复:
调整变量顺序,将port定义移到根路由之前:
const port = process.env.PORT || 5000 app.get('/', (req, res) => { res.send(`Server Working nice :), Your port being ${port}`) })
2. 前端axios请求Base URL缺失
如果前端项目与后端服务器运行在不同端口(比如前端3000、后端5000),直接使用相对路径/api/pizzas/getallpizzas会请求前端服务器,而非后端,导致404。
修复:
配置axios的Base URL指向后端服务器:
import axios from 'axios' // 创建带Base URL的axios实例 const api = axios.create({ baseURL: 'http://localhost:5000' // 替换为你的后端实际地址 }) export const getAllPizzas = () => async (dispatch) => { dispatch({ type: 'GET_PIZZAS_REQUEST' }) try { const response = await api.get('/api/pizzas/getallpizzas') console.log(response) dispatch({ type: 'GET_PIZZAS_SUCCESS', payload: response.data }) } catch (error) { dispatch({ type: 'GET_PIZZAS_FAILED', payload: error }) } }
3. Reducer状态拼写错误(非404直接原因,但需修复)
GET_PIZZAS_SUCCESS分支中,状态字段laoding拼写错误(应为loading),会导致组件无法正确识别加载状态。
修复:
case 'GET_PIZZAS_SUCCESS': return { loading: false, pizzas: action.payload }
4. 验证后端路由可用性
后端启动后,直接在浏览器或Postman访问http://localhost:5000/api/pizzas/getallpizzas:
- 若返回披萨数据:后端路由正常,问题出在前端请求配置
- 若仍返回404:检查路由文件是否正确引入、服务器是否挂载了
pizzasRoute
内容的提问来源于stack exchange,提问作者arshaikh0171
相关产品推荐
相关产品推荐

