[英]How can I send JSON with ExpressJS as UTF-8?
I've been struggling with a new web app I'm making. 我一直在努力开发一个新的Web应用程序。 In previous situations I cannot recall to have encountered this issue.
在以前的情况下,我不记得曾经遇到过此问题。 I'm testing with a very simple piece of code.
我正在用非常简单的代码进行测试。
var jsonToSend = {hello: "woørld"};
app.get('/someUrl', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(jsonToSend);
}
Output is: {"hello":"Woørld"}
with Content-Type:application/json; charset=utf-8
输出为:
{"hello":"Woørld"}
,其Content-Type:application/json; charset=utf-8
Content-Type:application/json; charset=utf-8
in the network tab. 网络标签中的
Content-Type:application/json; charset=utf-8
。 I also tried various attempts with JSON.stringify
and adding charset
to setHeader
, though it seems to be right in the network tab. 我还尝试了
JSON.stringify
各种尝试,并将charset
添加到setHeader
,尽管它似乎在network选项卡中正确。 How can I make sure the data is correctly encoded from the server? 如何确保服务器中的数据正确编码?
I use WebStorm and I checked file encoding to be UTF-8
. 我使用WebStorm并检查文件编码为
UTF-8
。
Try using res.set({ 'content-type': 'application/json; charset=utf-8' });
尝试使用
res.set({ 'content-type': 'application/json; charset=utf-8' });
: :
var jsonToSend = {"\"hello"\": "\"woørld"\"};
app.get('/someUrl', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.set({ 'content-type': 'application/json; charset=utf-8' });
res.send(jsonToSend);
}
I realized that the issue had to be towards my IDE. 我意识到问题必须出在我的IDE上。 So this answer would target those of you who are using WebStorm:
因此,此答案将针对使用WebStorm的您:
I had previously started a project on my windows computer which converted my source files to windows-1252 encoding instead of utf-8. 我以前在Windows计算机上启动了一个项目,该项目将源文件转换为Windows-1252编码而不是utf-8。 Make sure to do
Preferences > File Encoding
and set all encoding to UTF-8 and convert old files. 确保执行
Preferences > File Encoding
,并将所有编码设置为UTF-8并转换旧文件。 The file encoding is also marked in the settings view. 文件编码也在设置视图中标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.