vue使用axios请求常见方式

在使用axios时,注意到配置选项中包含params和data两者 ①params是添加到url的请求字符串中的,用于get请求。 ②data是添加到请求体(body)中的, 用于post请求。 vue开发推荐使用axios进行ajax异步请求,然而使用axios进行post表单提交时默认使用的Content-Type“为application/json” 而大多数的web服务器只能识别post请求头Content-Type为“application/x-www-form-urlencoded”,如下两种解决方法:

一、修改服务器端:使其能够接收Content-Type为application/json的请求(如springmvc添加@requestBody注解等等)

二、修改前端:axios中post提交数据的三种请求方式写法

1、Content-Type: application/json(默认)

import axios from axios
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log(res=>,res);            
})

2、Content-Type: application/x-www-form-urlencoded(普通表单提交、JQuery Ajax表单提交以及大多数web服务器默认识别的post请求头)

①使用qs(推荐使用)

在项目中使用命令行工具输入:npm install qs 安装完成后在需要用到的组件中:import qs from qs’ qs.parse()是将URL解析成对象的形式 qs.stringify()是将对象 序列化成URL的形式,以&进行拼接

import axios from axios
import qs from qs
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,qs.stringify({
    data
}))
.then(res=>{
    console.log(res=>,res);            
})

②使用URLSearchParams

import axios from axios
let data = new URLSearchParams()
data.append(code, 1234)
data.append(name, yyyy)
axios.post(`${this.$url}/test/testRequest`, data )
.then(res=>{
    console.log(res=>,res);            
})

PS:使用qs或URLSearchParams自动会把Content-Type设置为application/x-www-form-urlencoded,如果未自动设置,axios也支持自定义headers头

headers:{
    Content-Type:application/x-www-form-urlencoded
}

3、Content-Type: multipart/form-data

import axios from axios
let data = new FormData();
data.append(code,1234);
data.append(name,yyyy);
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log(res=>,res);            
})

参考地址:

经验分享 程序员 微信小程序 职场和发展