部署Express+React项目至Nginx服务器出现405错误求助
问题描述
我用Node.js + Express搭建后端,React做前端开发REST API,服务器采用Nginx。本地测试一切正常,但部署至服务器、构建React应用并启动Express服务后,通过域名访问时POST请求持续返回405错误:
XHRPOSThttps://example.com/api/someRequest
[HTTP/3 405 Method Not Allowed 53ms]Uncaught (in promise) Error: Request failed with status code 405
相关代码如下:
前端POST请求代码
import { post } from "@import/blahblah"; let response = await post("/someRequest");
@import/blahblah模块代码
import axios from "axios"; const isLocalHost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1"; export async function post(url, args = {}) { const Axios = axios.create({ withCredentials: true, baseURL: isLocalHost ? "http://localhost:5000/api" : "https://example.com/api", }); let response = await Axios.post(API_URL + url, args); return response.data; }
后端Express代码
const express = require('express') const cors = require('cors') const http = require('http') const cookieParser = require('cookie-parser') require('dotenv').config() // Create server connection const app = express() const server = http.createServer(app) // Set app uses app.use(express.json()) app.use(cookieParser()) app.use(express.urlencoded({ extended: true })) app.use( cors({ credentials: true, origin: process.platform === 'win32' ? 'http://localhost:3000' : 'https://example.com' }) ) server.listen(5000, () => console.log('Server - Started (port 5000)')) app.post('/api/someRequest', async (req, res) => { res.send(invite) })
解决方法
1. 修复Axios请求路径错误
你在@import/blahblah的post函数中已经设置了baseURL,但请求时又错误拼接了未定义的API_URL,导致请求路径异常。直接使用传入的url即可:
// 修改后代码 let response = await Axios.post(url, args);
2. 配置Nginx正确转发API请求
Nginx需要将https://example.com/api/*的请求转发到Express服务的5000端口,否则请求会落到React静态资源路由上,触发405错误。示例配置:
server { listen 443 ssl http2; server_name example.com; # SSL相关配置请自行补充 # 指向React构建后的静态资源目录 root /path/to/your/react/build; index index.html; # API请求转发到Express服务 location /api/ { proxy_pass http://localhost:5000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # React单页应用路由 fallback,避免刷新页面404 location / { try_files $uri $uri/ /index.html; } }
配置完成后执行sudo nginx -s reload重新加载Nginx配置。
3. 优化Express的CORS配置
当前用process.platform === 'win32'判断生产/开发环境不够可靠,建议改用环境变量控制:
// .env文件添加配置 NODE_ENV=production FRONTEND_URL=https://example.com // Express代码修改 app.use( cors({ credentials: true, origin: process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : process.env.FRONTEND_URL }) )
4. 调整Express路由注册顺序
虽然当前代码中server.listen()之后注册路由也能生效,但建议将路由定义放在服务启动之前,避免潜在的加载顺序问题:
// 先定义路由 app.post('/api/someRequest', async (req, res) => { res.send(invite) }) // 再启动服务 server.listen(5000, () => console.log('Server - Started (port 5000)'))
内容的提问来源于stack exchange,提问作者wnmarc
相关产品推荐
相关产品推荐

