nyoatype
nyoatype

Reputation: 41

Node.js response headers are not set

I'm trying to set Nodejs headers to the returned packet, but when logging the response it's always empty.

Here is my middleware in node.js server. It's supposed to add "From" header to the response, but it doesn't appear in the client logging the response.


EDIT:

In addition to changing res.set() to res.setHeaders() I had to access them at the client side using response.headers() instead of response.headers


app.use(function(reg, res, next){
        var checkAdmin = false;
        var bearerToken;
        var bearerHeader = reg.headers.authorization;
        if(admin.indexOf(reg.url) > -1){
                console.log("varmistetaan onko admin");
                checkAdmin = true;
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else if(public.indexOf(reg.url) < 0){
                console.log("varmistetaan onko suojattu");
                checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next);
        } else {
                bearerToken = decodeToken(bearerHeader);
                if(bearerToken !== false){
                        decoded = verifyToken(bearerToken);
                        if(decoded !== false){
                                if (checkIfExpired(decoded.expires)){
                                        res.setHeader('From','[email protected]');
                                        next();
                                }else{
                                        res.set('From','[email protected]');
                                        next();
                                }
                        }else{
                                res.set('From','[email protected]');
                                next();
                        }
                }else{
                        res.set('From','[email protected]');
                        next();
                }
        }
});

Here is my angularjs interceptor, which is logging the response at the moment:

.factory('authInterceptorService', ['$q', '$window', '$localStorage', function($q, $window, $localStorage){
        return {
                'request': function (config){
                        config.headers = config.headers || {};
                        if ($localStorage.accessToken) {
                                config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                        }
                        return config;
                },
                'response' : function(response){
                        console.log(response);
                        return response
                },
                'responseError': function(responseError){
                        responseError = JSON.parse(responseError.data);
                        if(responseError.tokenstatus === "expired"){
                                delete $localStorage.accessToken
                                window.location = "/";
                        }
                        if(response.status === 401 || response.status === 403) {
                                window.location = "/";
                        }
                        window.location = "/";
                        return $q.reject(response);
                }
        };
}])

This is what the response looks like:

{…}
config: {…}
cache: Object { put: put(), get: get(), remove: remove(), … }
headers: Object { Accept: "application/json, text/plain, */*", Authorization: "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcml2aWxlZ2VzIjp7ImFkbWluIjp0cnVlLCJhc3Vubm90IjpmYWxzZSwib3Bpbm5vdCI6ZmFsc2V9LCJvcHRpZXRvbWVtYmVyIjpmYWxzZSwiYXN1bm5vdG1lbWJlciI6ZmFsc2UsImV4cGlyZXMiOjE1MTYwNDA3MjksImlhdCI6MTUxNjAwNDcyOX0.hU8yT3G58ZtkJbBo-SUwLmcSMSX_8cHYxnX0GdmfJVM" }
jsonpCallbackParam: "callback"
method: "GET"
paramSerializer: function Ef/this.$get/<()
transformRequest: Array [ Df/this.defaults.transformRequest<() ]
transformResponse: Array []
url: "koti.html"
__proto__: Object { … }
data: "<h1>Tähän tulee kotisivun sisältö</h1>\n"
headers: wd/<() #Response headers should be here?
length: 1
name: ""
__proto__: function ()
status: 200
statusText: "OK"
__proto__: Object { … }

Upvotes: 1

Views: 3652

Answers (3)

user1353936
user1353936

Reputation: 124

I realize that the original question indicated the use of AngularJS, and while the responses for that are probably helpful, they DO NOT seem to apply to later versions of Angular (i.e. version 2+).

I was using NodeJS/express middlewares to host a secure form of json-server, and I was trying to dump the contents of the headers collection to the console to see that they all came across correctly. This is where I was going wrong, and here's why:

The headers property of the response object is not a method, but an object, and the headers are processed in a lazy-loaded manner. This means that dumping the contents to the console yielded an entirely empty collection, making me believe I had a bug. In order to access the full collection, you first need to call rsp.headers.init().

Now, if you do not need to see the full collection, feel free to make calls for the specific values you need, through calls such as rsp.headers.get("_returnCode"). When you make such calls, the init() method is called for you prior to attempting to return the first value, and all should work fine.

Hope this helps!

Upvotes: 0

Alqama Bin Sadiq
Alqama Bin Sadiq

Reputation: 358

res.setHeader()and res.writeHead() are a native method of Node.js and res.set() is a method from Express framework.

Documentation: res.setHeader(), res.set() res.writeHead

These three methods do exactly the same thing, set the headers HTTP response. The only difference is res.setHeader() and res.writeHead() allows you only to set a singular header and res.set() will allow you to set multiple headers. So use the one fit with your needs.

you can try any one of these: res.setHeader('From','[email protected]') or res.writeHead(200,{'Form':'[email protected]'})

Upvotes: 2

David Vicente
David Vicente

Reputation: 3111

Try with res.setHeader in all places (not res.set)

Upvotes: 0

Related Questions