实现步骤
1、后端Json服务需要加上请求头
// 指定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header("Access-Control-Allow-Methods:POST");
// 响应头设置
header("Access-Control-Allow-Headers:x-requested-with,content-type");
------------------------------------------如下实例-----------------------------------------------------------------------
@RequestMapping(value = "/roles",method = RequestMethod.GET)
@ResponseBody
public List<SYSRolesPojo> getRoles(HttpServletRequest request, HttpServletResponse response){
String originUrl = request.getHeader("Origin");
if (originUrl == null) {
originUrl = request.getHeader("Referer");
}
if (originUrl != null) {
String[] remoteUrl = originUrl.split("/");
String url = remoteUrl[0] + "//" + remoteUrl[1] + remoteUrl[2];
response.setHeader("Access-Control-Allow-Origin", url);
}
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setContentType("application/json;charset=UTF-8");
return sysRolesService.listRoles();
}
该服务从数据库查询角色数据返回一个json数组
[{
"roleID": 1,
"roleCode": "2001",
"name": "小小",
"description": null,
"pageNum": null,
"pageSize": null
}, {
"roleID": 2,
"roleCode": "2002",
"name": "经理",
"description": null,
"pageNum": null,
"pageSize": null
}, {
"roleID": 3,
"roleCode": "2003",
"name": "组长",
"description": null,
"pageNum": null,
"pageSize": null
}, {
"roleID": 4,
"roleCode": "2004",
"name": "组员",
"description": null,
"pageNum": null,
"pageSize": null
}, {
"roleID": 7,
"roleCode": "2001",
"name": "testPut",
"description": null,
"pageNum": null,
"pageSize": null
}]
2、前端vue,安装 axios和 VueAxios,然后调用
(1)使用vue-cli创建项目
使用脚手架安装项目: vue init webpack test 项目是基于webpack的
- Project name(工程名):回车
Project description(工程介绍):回车
Author:作者名
Vue build(是否安装编译器):回车
Install vue-router(是否安装Vue路由):回车
Use ESLint to lint your code(是否使用ESLint检查js代码):n
Set up unit tests(安装单元测试工具):n
Setup e2e tests with Nightwatch(是否安装端到端测试工具):n
Should we runnpm install
for you after the project has been created? (recommended):回车。
(2)启动项目
- 进入项目目录:cd test
- 安装项目所需要的依赖:npm install
- 启动项目:npm run dev
- 在浏览器中出现如下界面,说明项目创建成功
(3)停止项目,安装axios和VueAxios
使用ctrl+c 停止Npm ,运行如下命令
npm install --save --save-exact axios vue-axios
(4)修改main.js,引入包
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios)
(5)修改helloworld.vue,使用axios调用远程api
远程api http://api.komavideo.com/news/list ,可以替换为自己的api
此API由小马哥提供测试,官网http://api.komavideo.com/感谢小马哥的axios视频
<template>
<div class="hello">
<pre>{{content}}</pre>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
content: ""
}
},
mounted(){
this.axios.post("http://api.komavideo.com/news/list").then(body=>{
this.content=body.data;
});
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
运行结果
可以看到成功调用远程API