Next.js 14.1.0 Server Actions请求因头不匹配报错求助
解决Next.js 14.1.0 Server Actions "Invalid Server Actions request" 错误
问题原因
Server Actions的安全校验会同时验证origin请求头和x-forwarded-host请求头,当两者值不匹配时,即使allowedOrigins包含了两个地址,也会触发请求终止的错误。你的场景中x-forwarded-host是localhost:3000,origin是127.0.0.1:5500,二者不一致导致校验失败。
解决方案
方案1:配置允许的转发主机(推荐)
在next.config.ts的serverActions配置中添加allowedForwardedHosts,指定允许的x-forwarded-host值,和allowedOrigins配合使用:
/** @type {import('next').NextConfig} */ const nextConfig = { env: { BASE_URL: "http://localhost:8080/eNach" }, experimental: { serverActions: { allowedOrigins: ['http://127.0.0.1:5500'], allowedForwardedHosts: ['http://localhost:3000'] } } } module.exports = nextConfig
注意:移除allowedOrigins中的*,因为通配符和具体域名不能同时生效,Next.js会优先使用具体域名配置,通配符会被忽略。
方案2:统一请求的域名/IP
修改前端请求的地址,让origin和x-forwarded-host保持一致:
- 如果前端运行在
127.0.0.1:5500,确保请求Next.js时使用127.0.0.1:3000而非localhost:3000 - 或者启动Next.js时指定主机为
127.0.0.1(命令添加--hostname 127.0.0.1),同时前端请求地址也使用该IP
方案3:开发环境临时禁用校验(不推荐生产使用)
如果是本地开发调试,可以临时关闭Server Actions的origin校验:
experimental: { serverActions: { allowedOrigins: ['*'], disableOriginCheck: true } }
验证修改
修改配置后,重启Next.js服务,重新发起Server Actions请求,错误即可解决。
内容的提问来源于stack exchange,提问作者Abhinay Narayan Singh
相关产品推荐
相关产品推荐

