express js encode headers to utf-8

2019-08-13 02:39发布

问题:

I am using express js 4.13.3 and nodejs 12 I am getting request with header name: "John D�m" I don't know even the encoding it has, so I don't know how to convert it. the result should be name: "John Döm"

this is the routing

var express = require('express')

var app = express();

app.configure(function () {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

app.get('/drivers', function(req,res){
res.send(req.headers["name"])
});

app.listen(3000);
console.log('Up: http://127.0.0.1:3000/');

I tried res.header("Content-Type", "application/json; charset=utf-8");

can I set express to encode? with middleware or something? thank you in advanced.

回答1:

For some reason this worked for me:

res.end(JSON.stringify(req.headers.name, null, 2), 'utf-8');

but not this:

res.send(req.headers.name)

So I ended up with:

    var string = req.headers.name;
    return res.send('<!DOCTYPE html><html> <head><meta charset="utf-8"></head><body>' +
        string +
    '</body></html>');