javascriptnode.jsexpressrequest-headersnodejs-server

'req.headers is not a function' while trying to pass headers from client to nodejs server


I have a frontend that makes a call to my proxy server, which then makes a call to an Application API. I am trying to pass my header from the UI to the backend, but I am getting a TypeError: req.headers is not a function

Here's what I am doing. What am I missing or doing wrong?

UI


const requestnames = axios.create({
    baseURL: "http://localhost:3000",
    headers: {
        "x-id-key":
          "aaaaaaaaaaaaaaaaaaaaaaaa",
      },
  });

  export const getNames = () => {
    return requestnames.get("/names", {});
  };

backend

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) => {
    let myHeader = req.headers("x-id-key")
    apicall.get("/names", myHeader).then((data) => res.send(data.data));
};

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

Solution

  • req.headers is an object and not a function, but you generally don't want to read from that object directly because headers are case insensitive (meaning users could pass x-id-key or X-ID-KEY and they're effectively the same). Instead, you want to use req.get('x-id-key') to reliably read any request headers in a case insensitive way. If you want to live dangerously and encounter random hard-to-track bugs, you can access the headers directly with bracket notation: req.headers['x-id-key'], but I do not recommend this.