首页 > 编程语言 > 详细

Vue跨域请求的前端设计与java web后端设计示例

时间:2021-02-04 15:25:25      阅读:47      评论:0      收藏:0      [点我收藏+]

一、前端设置

1、必须安装axios以便实现ajax请求,安装方法是在项目路径处运行命令npm install --save axios。

2、修改src/main.js文件,添加以下第5到9行代码,改成以下的样子:

 1 import Vue from vue
 2 import App from ./App
 3 import router from ./router
 4 
 5 let axios=require(axios)//使用axios完成ajax请求
 6 axios.defaults.baseURL=http://localhost:8080//后端的地址和端口
 7 axios.defaults.withCredentials=true
 8 Vue.prototype.$axios=axios
 9 Vue.config.productionTip = false
10 
11 /* eslint-disable no-new */
12 new Vue({
13   el: #app,
14   router,
15   components: { App },
16   template: <App/>
17 })

3、修改config/index.js文件,增加下述的第7到15行代码

 1 module.exports = {
 2   dev: {
 3 
 4     // Paths
 5     assetsSubDirectory: static,
 6     assetsPublicPath: /,
 7     proxyTable: {
 8       /api:{
 9           target:http://localhost:8080,
10           changeOrigin: true,
11           pathRewrite:{
12               ^/api: /
13           }
14       }
15     },

4、前端页面的请求方法,其中请求地址"/access/test"是指后端地址"http://localhost:8080/access/test":

 1 methods:{
 2      load(){
 3         alert("加载成功!");
 4       },
 5      req(){
 6        var that=this;
 7        alert("发出请求");
 8        this.$axios.get("/access/test").then(res=>{
 9          alert("请求成功啦!"+res.data);
10        }).catch(err=>{
11          alert("出错啦!");
12        });
14      }
15     }
16   };

5、后端对应的test.java里的doGet方法里,注意增加第2、3这两行代码,其中的http://localhost:8081是请求的前端地址和端口。

1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2         response.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
3         response.setHeader("Access-Control-Allow-Credentials", "true");
4         response.setCharacterEncoding("utf-8");
5         response.getWriter().print("1");
6     }

 

http://localhost:8080

Vue跨域请求的前端设计与java web后端设计示例

原文:https://www.cnblogs.com/wwwzgy/p/14371872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!