vue2.0中使用axios进行(put,post请求时),遇到415错误
一、vue创建request工具类
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
baseURL: 'http://localhost:8090',
timeout: 10000
})
service.interceptors.request.use(
config => {
return config
},
error => {
Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (res.code < 0) {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject('error')
} else {
return response.data
}
},
error => {
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
二、创建api请求
orderInfo:{
userName:'王五',
...............
}
import request from "@/utils/request";
const api_name='/api/Pay'
export default {
nativePay(orderInfo){
return request({
url: `${api_name}/native`,
method:'post',
data:orderInfo,
headers:{
'Content-Type' : 'application/json;charest=UTF-8'
}
})
},
}
三、导入Json处理器依赖包
<!--json处理器-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
四、接收请求响应
@CrossOrigin
@RestController
@RequestMapping("/api/Pay")
@Api(tags = "微信支付")
@Slf4j
public class Controller {
@ApiOperation("微信支付下单")
@PostMapping("native")
public R nativePay(HttpServletRequest request, HttpServletResponse response) throws Exception {
Gson gson = new Gson();
Map<String ,String> map = new HashMap<>();
String body = HttpUtils.readData(request);
Map<String,Object> bodyMap = gson.fromJson(body,HashMap.class);
String userName= (String) bodyMap.get("userName");
return R.ok().data("userName",userName);
}
}
R类
@Data
@Accessors(chain = true)
public class R {
private Integer code;
private String message;
private Map<String,Object> data=new HashMap<>();
public static R ok(){
R r = new R();
r.setCode(0);
r.setMessage("成功");
return r;
}
public static R error(){
R r = new R();
r.setCode(-1);
r.setMessage("失败");
return r;
}
public R data(String key,Object value){
this.data.put(key, value);
return this;
}
}
|