接 上篇登陆接口
代码很简单 但是在写的时候出现了用axios传递参数 但是后台接收不到,一直undefined
admin.post('/register', async (req, res) => {
const { username, email, password } = req.body
let user = await User.findOne({ email })
if (user) {
console.log(req.body)
res.send('用户名已存在')
} else {
User.create({
username,
email,
password,
})
.then(() => {
res.send('ok')
})
.catch((err) => {
res.send(err)
})
}
})
假如html是用ajax传递参数的是没有问题的,
$('.register').on('click', function () {
$.ajax({
type: 'post',
url: 'http://localhost:3000/admin/register',
data: {
username: $('#name').val(),
email: $('.email').val(),
password: $('.password').val(),
},
success: function (res) {
console.log(res)
},
})
return false
})
但是在用axios的时候出现问题了,后台打印req.body以及传递过来的参数是这个样子的 传递过来的是字符串 这是为什么呢
let btn = document.querySelector('.register')
btn.onclick = async () => {
const res = await axios.post('http://localhost:3000/admin/register', {
username: document.getElementById('name').value,
email: document.querySelector('.email').value,
password: document.querySelector('.password').value,
})
console.log(res)
}
application/json ,axios默认提交就是使用这种格式。如果使用这种编码方式,那么传递到后台的将是序列化后的json字符串。如果在处理application/json时后台还是采用对付application/x-www-form-urlencoded的方式将会产生问题。例如后台node.js依然采用之前对付application/x-www-form-urlencoded的方法,那么得到的数据是这样子的
解决办法
既然我们知道axios post方法默认使用application/json格式编码数据,那么解决方案就有两种,一是后台改变接收参数的方法,另一种则是将axios post方法的编码格式修改为application/x-www-form-urlencoded,这样就不需要后台做什么修改了。