Node.js/Express-如何设置响应字符编码?
问题描述:
说我明白了
app.get('/json', function(req, res) {
res.set({
'content-type': 'application/json'
}).send('{"status": "0"}');
});
我正在尝试以UTF-8格式发送响应,但没有成功:
I'm trying to send the response as UTF-8 with the following with no success:
app.get('/json', function(req, res) {
// From Node.js Official Doc
// http://nodejs.org/api/http.html#http_http_request_options_callback
res.setEncoding('utf8');
res.set({
'content-type': 'application/json'
}).send('{"status": "0"}');
});
在Express中设置字符编码的正确方法是什么?
What is the correct way to set character encoding in Express?
答
使用res.charset: http ://expressjs.com/api.html#res.charset
Use res.charset: http://expressjs.com/api.html#res.charset
res.charset = 'value';
res.send('some html');
// => Content-Type: text/html; charset=value
但是,JSON默认情况下为UTF-8,因此您无需进行任何设置.
However, JSON is UTF-8 by default so you don't need to set anything.