0

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);
Tini
  • 169
  • 8
  • Just a suggestion, If this header is mandatory than you should add validation in your middleware to check if you are able to fetch all mandaotry paramters from req headers, body, parameters or not. It any mandatory paramter is missing than you should send response right away from middleware. – Munam Tariq Mar 19 '23 at 20:54

1 Answers1

1

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.

Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96