React配置Apollo请求头后Node.js API无法获取该请求头
问题原因与解决方法
你的代码核心问题是没有正确将自定义字段加入HTTP请求头,而是把headerData作为Apollo上下文的额外属性,而非请求头的一部分,所以Node.js后端无法在req.headers里读到它。
修正步骤
- 必须在
setContext的返回值里,将自定义头放到headers对象中,而非和headers平级 - HTTP请求头名称要符合规范:避免驼峰命名,建议用短横线分隔(比如
x-header-data),浏览器/服务器会自动将头名转为小写,后端读取时要对应使用小写键
修正后的代码
export const headerData = { data: null }; const httpLink = createHttpLink({ uri: 'http://localhost:4300/graphql' }) const authLink = setContext((_, { headers }) => { return { headers: { ...headers, // 使用符合HTTP规范的头名称,将值放入headers对象 'x-header-data': headerData.data } } }) const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() });
后端读取注意事项
在Node.js(比如Express)中,请求头会被自动转为小写,所以要通过小写的键读取:
// 后端代码示例 app.use('/graphql', (req, res) => { const headerValue = req.headers['x-header-data']; console.log(headerValue); });
如果headerData.data是复杂类型(比如对象),需要先转为JSON字符串再传入,后端再解析:
// 前端修改 'x-header-data': JSON.stringify(headerData.data) // 后端解析 const headerValue = JSON.parse(req.headers['x-header-data']);
内容的提问来源于stack exchange,提问作者mfusco
相关产品推荐
相关产品推荐

