zoukankan      html  css  js  c++  java
  • 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'
              });
            }
     
  • 相关阅读:
    防抖函数
    锁屏功能
    配置编译环境和线上环境之间的切换
    vue-router中的滚动行为
    axios的再次封装
    Anaconda 镜像配置
    Python 包管理工具 pip 与 conda
    Anaconda 安装与卸载
    VS Code 配置和使用
    解决 VS Code 无法使用Ctrl+C等快捷键
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/11125447.html
Copyright © 2011-2022 走看看