具体来说,请求方式和请求参数的对应关系如下:
Content-Type
● 这里设置的 Content-Type ,作用是告知服务器,浏览器提交的数据是何种类型的。
○ 值为:application/x-www-form-urlencoded(需要自己指定) ,表示客户端提交的是查询字符串。
○ 值为:application/json(需要自己指定) ,表示客户端提交的是 JSON 字符串。
○ 值为:multipart/form-data(xhr对象会自动设置),表示客户端提交的是 FormData 对象。
axios
get请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 获取远端图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});