简体   繁体   中英

NodeJS http server response headers are blank when headers are set for a request

So I'm sending a request via ajax and I'm setting the headers there and I can log and see that the headers are indeed being set

$.ajax({
    headers: {
        Authorization: localStorage.getItem('t')
    },
    type: 'GET',
    dataType: 'json',
    url: `/updatebackground?b=${bg}`,
    success: function(data) {
        console.log('yay');
    },
    complete: function() {
        console.log(this.headers)
    }
});

But when I try to log the headers in node they come back as blank

http.createServer(async (req, res) => {
    console.log(JSON.stringify(res._headers));
});

logs "{}" I'm unsure as to why this happens and any help would be appreciated

Apparenly it works with req.headers.authorization Doesn't really make sense as to why it's lowercase but eh whatever. I'll keep this here for anyone else with the same issue.

On the server, you're trying to access the headers on the response object, not the request object. Since the client set the headers on the request the desired headers would be on the request, or req .

If you change that server-side code to:

http.createServer(async (req, res) => {
    console.log(req.headers);
});

You will see the request headers

This is because you are logging the res headers and not the req headers.

the proper code for logging the request headers is:

http.createServer(async (req, res) => {
    console.log(JSON.stringify(req.headers));
});

res._headers is for setting the headers for the response that is sent by the server to client as the request's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM