1. 准备工作
npm install axios
2. 示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/axios/dist/axios.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item, index) in users" :key="index">
{{ item }}
</li>
</ul>
</div>
<script>
let vm = new Vue({
data() {
return {
users: []
}
},
methods: {
getData() {
axios.get('http://localhost:8080/getData', {
params: {
id: 1
}
})
.then(function (response) {
vm.users = response.data
})
.catch(function (error) {
console.error(error)
});
}
},
mounted() {
this.getData();
},
}).$mount('#app')
</script>
</body>
</html>
后端代码:
@GetMapping("/getData")
public ResponseEntity<List<String>> getData(Long id, HttpServletResponse response) {
System.out.println(id);
response.addHeader("access-control-allow-origin", "*");
return new ResponseEntity(Arrays.asList("zhangsan", "lisi", "wangwu"), HttpStatus.OK);
}
运行: 补充: 后端代码中如果不加这一行:
response.addHeader(“access-control-allow-origin”, “*”);
前端这边将报错:
has been blocked by CORS policy 这是浏览器 同源策略 问题,或者叫 跨域问题 。常见于用Chrome调试脚本的时候,需要加载的脚本和location不同源
|