10

Here is actual code that works well but i would like to check if my headers are well transmitted to my api:

var request = require('request');
var express = require('express');
var router = express.Router();

/* GET data by sportId */
router.get('/:locale/:sportId/:federationId/:date', function(req, res) {
    var date = req.params.date;
    var locale = req.params.locale;
    var sportId = req.params.sportId;
    var federationId = req.params.federationId;

   request(getEventsOptions(sportId, federationId, date, locale), function(error, response, body) {
    res.send(body);
   });
});

// get options for request
function getEventsOptions(sportId, federationId, date, locale)
{
    return {
        url: `http://myapi.com/event/sport/${sportId}/date-from/${date}`,
       headers: {
         'accept': 'application/json',
         'dateTo': date,
         'federationIds': federationId,
         'X-Application-ID': 'sporter',
         'Accept-Language': locale,
     }
   };
}

So my question is quite general, how can i check headers of my call in a node js app ?

galkin
  • 5,264
  • 3
  • 34
  • 51
yoyojs
  • 1,723
  • 5
  • 24
  • 41
  • 1
    Generally talking, you can retrieve your headers with the inject request object as in `var xtoken = req.headers['x-token'];`. – Rafael Araújo Sep 19 '18 at 15:22
  • could u provide me an example because when i console log this in in my route the headers are not at all those i use in my request call – yoyojs Sep 19 '18 at 15:36
  • In your case, you could try `const authorization = req.headers['authorization']` to retrieve Authorization header. – Rafael Araújo Sep 21 '18 at 18:33

3 Answers3

17

There are three ways to do this:

First, using req.get function:

req.get('headerName');

Second, using req.header function:

req.header('headerName');

Third, using req.headers actual object:

req.headers['headerName'];

I hope it helps you.

MahanTp
  • 744
  • 6
  • 16
  • const secure = req.secure || req.headers(x-forwarded-proto')=== 'https' Had this in my code and was getting above error so modified to below and it worked! const secure = req.secure || req.headers['x-forwarded-proto']=== 'https' – utkarsh-k May 22 '21 at 19:06
4

According documentation you need req.get function. Also you can use req.headers object with all sended headers.

Code example:

const request = require('request');
const express = require('express');
const router = express.Router();

router.get('/:locale/:sportId/:federationId/:date', (req, res) => {
  // destructuring assignment for better readability
  const { date, locale, sportId, federationId } = req.params;

  // header example with get
  const authHeader = req.get('Authorization');
  console.log(authHeader);
  // example with headers object
  console.log(req.headers);


  request(getEventsOptions(sportId, federationId, date, locale), (error, response, body) => {
    res.send(body);
  });
});

function getEventsOptions(sportId, federationId, date, locale) {
  return {
    url: `http://myapi.com/event/sport/${sportId}/date-from/${date}`,
    headers: {
      'accept': 'application/json',
      'dateTo': date,
      'federationIds': federationId,
      'X-Application-ID': 'sporter',
      'Accept-Language': locale,
    }
  };
}
galkin
  • 5,264
  • 3
  • 34
  • 51
  • i get this result : undefined { host: 'localhost:3000', 'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0', accept: 'application/json, text/plain, */*', 'accept-language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3', 'accept-encoding': 'gzip, deflate', referer: 'http://localhost:3333/', origin: 'http://localhost:3333', connection: 'keep-alive', 'if-none-match': 'W/"273c3-JNzLHhWM4+cF/xoMYKC2I"' } so it seems i don't see any of the headers i send – yoyojs Sep 20 '18 at 09:42
  • 1️⃣`req.headers` and `req.get` definitely work. You can easily check that with postman. 2️⃣You have mistake at your methods to send request to your application. – galkin Sep 20 '18 at 09:50
  • ok so its the way i pass the headers options that is not good. but the weird thing is that i receive the good events from my api with the date, federation and locale. – yoyojs Sep 20 '18 at 09:54
  • Maybe they has default values? But this discussion is not part of your question. Please, mark answer correct if you receive answer or update question. If you will need help from community, you can open new question any time. Cheers! – galkin Sep 20 '18 at 10:01
1

If you want to check the headers for all incoming api-calls you could also use express middleware.

This example checks an auth-token on all api calls

const router = express.Router();

router.use((req, res, next) => {
    const headers = req.headers
    const clientToken = headers["authorization"] || headers["x-access-token"];
    const serverToken = process.env.TOKEN;
    const verified = clientToken === serverToken;

    if (!verified) {
        return res.status(400).send("Invalid token.");
    }
    next();
});


// followed by your api routes
// router.get("/api/", ...)