前端发送数据后端进行验证遇到的错误
1.客户端发送到的地址
我的客户端开启在8080端口,服务端开启在8081端口,先在vue中config.js中配置代理地址 target: 'http://localhost:8081'
,然后在用ajax发送请求,然后发送请求就可以请求到服务端的端口
config.js代理配置
devServer: {
proxy: {
'/api': {// 匹配所有以 '/api'开头的请求路径
target: 'http://localhost:8081',// 代理目标的基础路径
changeOrigin: true,
//pathRewrite: { '^/api': '' }//将/api替换成空白
}
}
}
Ajax发送post请求
sendInfo(){
axios.post('http://localhost:8081/api/login', {
data: {
username: this.username,
password: this.password
}
}, {
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
console.log(res.data)
if(res.data.success){
this.$router.replace('/homePage')
}
}).catch((error) => {
console.log(error);
});
2.进入服务端接口,但是接受数据为undefined
客户端发送数据username = 'luxiaotao'
到客户端对应的接口中的req中,接受数据const userinfo=req.body
,接收数据的格式userinfo.data.username
错误点:接收格式写成userinfo.username
,教训:以后可以先从底层看起,console.log(userinfo)
,输入之后才知道要的数据被封装到data里边