【发布时间】: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