node expressはjsonデータをフロントエンドに返す

2876 ワード

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