解决node.js响应乱码
var http = require('http')
var server = http.createServer()
server.on('request',function (req,res) {
console.log('收到客户端的请求了, 请求路径是:' + req.url)
var url = req.url
var products =[
{name:'苹果 X',price:8888, }, {name:'菠萝 X',price:6000,},{ name:'小辣椒 X',price:1999, }
]
if(url == '/products'){
res.end(JSON.stringify(products))
}else{
res.end('err')
}
})
server.listen(3000,function(){
console.log('服务器启动成功了,可以通过 http://127.0.0.1:3000/来访问')
})`
有这样的乱码
在res.end(JSON.stringify(products))上面加
res.writeHead(200, {‘Content-Type’: ‘text/html; charset=utf-8’});
如下
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
res.end(JSON.stringify(products))
就好啦