如何在 Node.js 中获取 UTF-8? [英] How to get UTF-8 in Node.js?

查看:35
本文介绍了如何在 Node.js 中获取 UTF-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的 API 上获得 UTF-8 支持?目前,一个字符串输出如下:

How do I get UTF-8 support on my API? At the moment, a string outputs like this:

name: "John D�m"

代替:

name: "John Döm"

在下面结帐 app.js:

Checkout app.js below:

var express = require('express'),
    driver = require('./driver');

var app = express();

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

app.get('/drivers', driver.findAll);

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

推荐答案

挂钩响应生成器或创建执行以下操作的中间件:

Hook into you response generator or create a middleware that does the following:

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

否则浏览器会以他喜欢的编码显示内容.

Otherwise the browser displays the content in his favorite encoding.

如果这对您没有帮助,那么 DB 的编码可能有误.

If this doesn't help you DB is probably in the wrong encoding.

由于答案已经有将近 5 年的历史了,因此 API 发生了变化.对于当前的 node.js 版本,请使用:

Since the answer is nearly 5 years old, the API has changed. For current node.js versions use:

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

这篇关于如何在 Node.js 中获取 UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆