You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 19:12:18