【问题标题】:async await axios post data with vue js, the data send is different between vue and postmantasync await axios用vue js发布数据,vue和postmant发送的数据不一样
【发布时间】:2022-03-13 13:54:09
【问题描述】:

我尝试使用 vue js 创建数据,但后端无法读取数据,只是将“未定义”发送到数据库,我尝试使用邮递员创建数据,后端可以读取数据,

我看到后端抓到的数据,原来是vue js端发送的数据和postman发送的数据有区别

这是邮递员发送的数据

[Object: null prototype] { name: '6', email: '5', password: '3' }

这里是vue js发送的数据

[Object: null prototype] {
  '{"name":"2","email":"2","password":"2"}': ''
}

这是vue js中的脚本

<script>
  import axios from "axios";
  export default {
    name: 'AddUser',
    data(){
      return {
        model: {
          name: '',
          email: '',
          id_status: '',
          password: '',
        }
      };
    },
    methods: {
      async saveUser(){
        try{
          const response = await axios.post('http://localhost:8000/users',this.model);
          res.data.headers['Content-Type'];
          console.log(response);
        } catch (err){
          console.log(err);
        }
      }
    },
  };
</script>

这里是 node js 中的脚本作为后端

if(q.pathname == "/users" && req.method == "POST"){
        var body = '';
        req.on('data', function(data){
            body += data;
            if(body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function(){
            var postData    = qs.parse(body);
            let name        = postData.name;
            let email       = postData.email;
            let id_status   = postData.id_status;
            let password    = postData.password;            
            let sql = `insert into users (name,email,id_status,password) values ('${name}','${email}','${id_status}','${password}')`
            console.log(postData)
            db.query(sql,(err, result) => {
                if (err) throw err;

                if(result.affectedRows == 1){
                    res.end(JSON.stringify({message: 'success'}));
                }else{
                    res.end(JSON.stringify({message: 'failed'}));
                }   
            });
        });

【问题讨论】:

  • 尝试在axios.post请求之前查看this.model实际上是什么。
  • 在 axios 之前 this.model like this { name: '1', email: '1', password: '3' }
  • 所以这是一个对象,而不是一个字符串?要检查的另一件事是浏览器开发工具中的网络选项卡。它应该显示请求是如何发送的,带有标题和正文。

标签: javascript node.js vue.js async-await axios


【解决方案1】:

问题解决了,我只是改变

var postData    = qs.parse(body);

var postData    = JSON.parse(body);

感谢您的帮助

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2017-09-27
  • 2021-09-21
  • 2020-05-18
  • 2021-11-23
  • 2021-10-20
  • 2020-10-16
  • 2018-03-22
  • 2021-07-03
  • 2020-02-27
相关资源
最近更新 更多