node express返回json数据给前端

请注意,使用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'
          });
        }
 
原文地址:https://www.cnblogs.com/mmzuo-798/p/11125447.html