Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13787

how to send headers in response nodejs

I'm trying to send headers fields in response value as follow:

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');

var app = express();

app.use(cors({
    'allowedHeaders': ['sessionId', 'Content-Type'],
    'exposedHeaders': ['sessionId'],
    'origin': '*',
    'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
    'preflightContinue': false
  }));

app.use('/', function(req, res){
        var data = {
          success: true,
          message: "Login success"
        };
        res.setHeader('custom_header_name', 'abcde');
        res.status(200).json(data);
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

Problem is headers value went undefined when I try to call inside $http and fetch. Please let me know what I've missed?

fetch

fetch('http://localhost:3000').then(function(response) {
  console.log(JSON.stringify(response)); // returns a Headers{} object
})

$http

$http({
    method: 'GET',
    url: 'http://localhost:3000/'
}).success(function(data, status, headers, config) {
    console.log('header');
    console.log(JSON.stringify(headers));
}).error(function(msg, code) {

});

Upvotes: 1

Views: 128

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

You have to use headers.get to retrieve the value of a specific header. The headers object is an iterable, you can use for..of to print all its entries.

fetch('http://localhost:3000').then(function(response) {

    // response.headers.custom_header_name => undefined
    console.log(response.headers.get('custom_header_name')); // abcde

    // for(... of response.headers.entries())
    for(const [key, value] of response.headers) {
        console.log(`${key}: ${value}`);
    }
})

An object implementing Headers can directly be used in a for...of structure, instead of entries(): for (var p of myHeaders) is equivalent to for (var p of myHeaders.entries()).

Check the docs for more information.


Working example

fetch('https://developer.mozilla.org/en-US/docs/Web/API/Headers').then(function(response) {

    console.log(response.headers.get('Content-Type')); // Case insensitive

    for(const [key, value] of response.headers) {
        console.log(`${key}: ${value}`);
    }
})

Upvotes: 1

Related Questions