Xalsar
Xalsar

Reputation: 83

Cant set HTTP headers in express

I have been struggling to implement headers to my application, so I decided to copy some stack overflow code to be sure that I was not committing any typo:

addToHeader = function (req, res, next) {
    console.log("add to header called ... " + req.url);
    res.header('X-XSS-Protection', '0');
    next();
}

app.post('/processLogIn', addToHeader, async (req, res) => {
    console.log(req.headers)
    res.send()
})

Unfortunately, the problems persist since X-XSS-Protection does not appear in the headers:

{ host: 'localhost:3000',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  referer: 'http://localhost:3000/logIn',
  'content-type': 'application/x-www-form-urlencoded',
  'content-length': '53',
  dnt: '1',
  connection: 'keep-alive',
  cookie: 'io=ws5aQuqAjplpBAZyAAAA',
  'upgrade-insecure-requests': '1',
  'cache-control': 'max-age=0' }

Following the documentation and stack overflow, I changed res.header to set and append but they give the exact same result.

Also, I have express installed and implemented correctly (v. ^4.16.3)

const express = require('express')
let app = express();

With set:

addToHeader = function (req, res, next) {
    console.log("add to header called ... " + req.url);
    res.set('X-XSS-Protection', '0');
    next();
}

Output:

{ host: 'localhost:3000',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  referer: 'http://localhost:3000/logIn',
  'content-type': 'application/x-www-form-urlencoded',
  'content-length': '53',
  dnt: '1',
  connection: 'keep-alive',
  cookie: 'io=ws5aQuqAjplpBAZyAAAA',
  'upgrade-insecure-requests': '1',
  'cache-control': 'max-age=0' }

Upvotes: 1

Views: 1928

Answers (2)

user14339485
user14339485

Reputation:

If you're trying to set a response header and not an HTTP header, the above code is perfectly fine. I had the same problem, that's when I realized I was on the HTTP header tab and not the response header tab in Postman.

Let me know if this works. Thanks

Upvotes: 0

Brad
Brad

Reputation: 163752

The code you're using is wrong. Use .set().

res.set('X-XSS-Protection', '0');

https://expressjs.com/en/4x/api.html#res.set

Upvotes: 2

Related Questions