如何在Next.js重写中传递请求体参数?
问题分析与解决方案
核心问题
你遇到的错误本质是请求体格式与Content-Type不匹配,而非Next.js重写规则的问题:
- 你设置了
Content-Type: application/x-www-form-urlencoded,但用JSON.stringify()将参数转为JSON字符串,导致IdentityServer4无法解析出client_id等必填参数,从而抛出"No client identifier found"错误。
分步解决
1. 修正前端请求的body格式
将JSON对象转为application/x-www-form-urlencoded格式的字符串,使用URLSearchParams来处理:
const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: "password", client_id: "client", client_secret: "clientsecret", username: "matias@gmail.com", password: "12341234" }) }; // 使用相对路径触发Next.js重写规则 const token = fetch("/connect/token", requestOptions) .then(response => response.json()) // 解析响应为JSON格式 .then(data => console.log(data)) .catch(error => console.log(error));
2. 确认Next.js重写规则有效性
你的重写配置本身是正确的,可添加日志验证环境变量是否生效:
const nextConfig = { reactStrictMode: false, async rewrites() { console.log("当前运行环境:", process.env.NODE_ENV); return process.env.NODE_ENV === "development" ? [ { source: "/connect/token", destination: "http://localhost:4446/connect/token", } ] : []; }, }; module.exports = nextConfig;
Next.js的重写规则会自动转发请求的方法、请求头和请求体,只要前端请求格式正确,参数就会被正常传递到目标服务器。
3. 验证结果
启动开发服务器后重新发送请求,查看IdentityServer4的日志,若参数解析正常,错误会消失,同时能正常获取token。
内容的提问来源于stack exchange,提问作者Falcon Stakepool
相关产品推荐
相关产品推荐

