在一篇文章中,我们说了如果在后端接收POST请求(JSON类型和x-www-form-urlencoded类型),不过使用的是Postman来模拟前端发送请求的。
这篇文章将展示使用在vue.js框架中如何发送请求。
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。Axios官方说明文档
var map = {//JSON数据名称-值对
"username":this.user.name,
"password":this.user.pass
}
this.$axios.post(
'/login'//自己提供的API接口 如果自己没有写的话,可以直接写 提交的url(例如:http://localhost:8080/BookShopOfSpring2/api/getAllBookByType)
,map)
.then((response)=>{
flag=response.data;
})
.then( (res)=>{
if (flag==true) {
this.$notify({
type: 'success',
message: '欢迎用户'+this.user.name,
duration: 3000
})
} else {
this.$message({
type: 'error',
message: '用户名或密码错误',
showClose: true
})
}
})
.catch( (err)=>{
console.log(err);
})
下面这种形式的也可以:
axios.post('/user', {//官方格式
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
要注意的是 axios 默认编码类型是 application/json。如果想要修改默认的编码方式,在vue.js框架中的main.js文件中,添加:
import axios from 'axios'//引入axios
axios.defaults.baseURL = 'https://api.example.com';//设置默认请求地址
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//Web API 验证
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//设置默认编码方式为
也可以直接在请求中设置请求头:
this.$axios({
method: 'post',
url: 'http://www.17huo.com/tusou/deeplorSearch.html',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: { imgFile: url },//data是添加到请求体(body)中的, 用于post请求。
//params: { imgFile: url }params是添加到url的请求字符串中的,用于get请求。
}).then(data => {
console.log(data)
})