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

从前端传Header到Node.js服务器时遇TypeError: req.headers is not a function错误

问题修复:TypeError: req.headers is not a function

核心错误点

  • req.headers不是方法:Express中req.headers是存储请求头的普通对象,必须用属性访问方式(req.headers["x-id-key"])获取头信息,不能像函数一样调用。
  • Axios请求参数格式错误:Axios的get方法第二个参数是配置对象,请求头需要嵌套在该对象的headers字段中,不能直接传递头值或头对象。

修复后的完整后端代码

const express = require("express");
const cors = require("cors");
const axios = require("axios");

const app = express();
const port = 3000;
app.use(cors());

const apicall = axios.create({
  baseURL: "https://bk/api/v1",
});

const getAllNames = (req, res) => {
    // 正确获取请求头
    const xIdKey = req.headers["x-id-key"];
    
    // 正确配置Axios请求头
    apicall.get("/names", {
      headers: {
        "x-id-key": xIdKey
      }
    })
    .then((response) => {
      res.send(response.data);
    })
    // 新增错误处理,避免请求失败时无响应
    .catch((error) => {
      console.error("调用上游API失败:", error);
      res.status(500).send("获取数据失败");
    });
};

app.get("/names", getAllNames);

可选优化

  • UI端的getNames函数可以简化,因为get方法的第二个配置参数为空时可以省略:
    export const getNames = () => {
      return requestnames.get("/names");
    };
    
  • 如果上游API要求必须携带x-id-key头,建议在后端添加校验逻辑,避免空值传递。

内容的提问来源于stack exchange,提问作者Tini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:22:13