Axios请求方式
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
使用cdn的方式引入axios.js
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"/>
使用这个注解可以使前端和后端跨域请求
@CrossOrigin
详细介绍
then成功的回调函数
catch请求失败的异常
params 参数
data请求体数据
axios中文网:https://www.kancloud.cn/yunye/axios/234845
GET请求
方式一:
axios({
method: 'get',
url: 'http://127.0.0.1:8081/getAxios',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
java后台接收
@ResponseBody
@RequestMapping(value = "/postAxios3", method = RequestMethod.POST)
public Object postAxios3(@RequestBody Map<String, Object> maps) {
Map<String, Object> map = new HashMap<>();
map.put("firstName", maps.get("firstName"));
map.put("lastName", maps.get("lastName"));
return map;
}
方式二:
axios.get('http://127.0.0.1:8081/getAxios', {
params: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
java后台接收
@RequestMapping(value = "/getAxios", method = RequestMethod.GET)
public String getAxios(String firstName, String lastName) {
return "成功=" + firstName + ":" + lastName;
}
POST请求
方式一:
axios({
method: 'post',
url: 'http://127.0.0.1:8081/postAxios',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
方式二:
var data = {"firstName":"Fred", "lastName":"lintstone"};
axios.post('http://127.0.0.1:8081/postAxios', data)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
java后台接收
@ResponseBody
@RequestMapping(value = "/postAxios", method = RequestMethod.POST)
public Object postAxios3(@RequestBody Map<String, Object> maps) {
Map<String, Object> map = new HashMap<>();
map.put("firstName", maps.get("firstName"));
map.put("lastName", maps.get("lastName"));
return map;
}