請注意,使用res.json()的格式
1.前面不能添加 res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
axios.post('xxx').then((response) => {
if (response.data.code === '200') {
// res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
// res.end("{'status':200, 'message': '上傳成功!'}");
res.json({status: response.data.code, message: '上傳成功'});
} else {
// res.writeHead(200, {'content-type': 'text/plain;charset=utf-8'});
res.json({status: response.data.code, message: response.data.msg});
}
})
這里 res.writeHead()需要配和 res.end()使用但是res.json()不需要添加header了,否則會報錯

2、還說明一點用 res.json() 返回個前端的數據就是json格式的,不是json字符串,這一點請和res.end('xxx')返回的是json字符串做區別開
前端接收代碼
axios.post('/upload', formData).then((res) => {
console.log(res.data) // {status: '478', message: 'JSON格式不對'}
console.log(typeof res.data) // object
const data = res.data
if (data.status === '200') {
_this.$message({
message: '上傳成功!',
type: 'success'
});
} else {
_this.$message({
message: data.message,
type: 'error'
});
}
