当表单提交包含中文数据时,Node服务端使用decodeURI或者decodeURIComponent解析时可能会出现&#…的情况。
引入html-entities模块
//在项目的根目录中下载此模块
npm install html-entities --save
在node_modules中多出了html-entities模块,然后直接用就行。
以下是我的简单源代码
const http = require('http'),
querystring = require('querystring'),
Entities=require('html-entities').Html5Entities
http.createServer(function (req, res) {
if (req.url === '/') {
res.writeHead(200, {
'Content-Type':'text/html'
})
res.end(['<form method="post" action="/url">',
'<fieldset>',
'<legend>form</legend>',
'<input type="text" name="username"/>',
'</fieldset>',
'</form>'].join(''))
} else if (req.url === '/url' && req.method == 'POST') {
let body = ''
req.on('data', function (data) {
body += data
})
req.on('end', function () {
res.writeHead(200, {
'Content-Type': 'text/plain;charset=utf-8',
})
const obj = querystring.parse(body),
entities = new Entities(),
username=entities.decode(obj.username)
console.log(body)
console.log(username)
res.end('hello '+username)
})
}
}).listen(3000)