Next.js本地请求Node.js接口遇CORS错误,求解决方案
解决Next.js向Node.js后端发送POST请求的CORS问题
首先检查你的Next.js请求代码,URL存在语法错误:
// 错误写法:多了一个多余的单引号 const url = `http://localhost:8000'/events`; // 正确写法 const url = `http://localhost:8000/events`;
这个语法错误可能是请求失败的直接原因,先修正它。如果修正后仍存在CORS问题,可尝试以下方案:
方案一:确认Node.js的CORS中间件加载顺序
确保CORS中间件在所有路由之前加载,否则路由不会应用CORS规则:
const express = require('express'); const cors = require('cors'); const app = express(); // 先加载CORS中间件 app.use(cors({ origin: '*' })); // 再加载解析JSON的中间件和业务路由 app.use(express.json()); app.post('/events', (req, res) => { // 处理请求逻辑 res.json({ message: '请求已接收', data: req.body }); }); app.listen(8000, () => console.log('服务运行在8000端口'));
方案二:使用Next.js API路由作为代理(推荐)
Next.js推荐通过内部API路由转发请求,避免前端直接跨域。在pages/api目录下创建events.js文件:
// pages/api/events.js export default async function handler(req, res) { if (req.method === 'POST') { try { const response = await fetch('http://localhost:8000/events', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(req.body), }); const data = await response.json(); res.status(response.status).json(data); } catch (error) { res.status(500).json({ error: '转发请求失败' }); } } else { res.setHeader('Allow', ['POST']); res.status(405).end(`Method ${req.method} Not Allowed`); } }
之后在前端页面中,请求这个内部API路由:
const url = '/api/events'; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: "Jon" }) }); const response = await res.json(); console.log(response);
这种方式不会触发浏览器的CORS检查,因为前端请求的是同域的Next.js服务,再由Next.js转发到Node.js后端。
方案三:在Next.js配置文件中添加重写规则
在next.config.js里配置路径重写,将前端请求路径映射到Node.js后端:
// next.config.js module.exports = { async rewrites() { return [ { source: '/api/events', destination: 'http://localhost:8000/events', }, ]; }, };
前端请求路径同样使用/api/events,调用方式与方案二一致。
内容的提问来源于stack exchange,提问作者Akbar Sheikh
相关产品推荐
相关产品推荐

