vue前端与Java后端进行跨域交互

这篇具有很好参考价值的文章主要介绍了vue前端与Java后端进行跨域交互。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.后端的几种解决方法

1.在Controller上面加上@CrossOrigin

2.写一个配置文件并且在Controller层加上注解@CORSConfig

package com.wolwo.langyage.base.util;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * CORS configuration
 */
@Configuration
public class CORSConfig {
 
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://127.0.0.1:8080,http://localhost:8080")
                        .allowedMethods("POST,GET, OPTIONS,DELETE,PUT")
                        .allowedHeaders("Content-Type,ContentType,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With")
                        .allowCredentials(true);
            }
        };
    }
 
}

3.在springmvc配置文件里加入

4.写一个过滤器类并且在web.xml中注册过滤器

package com.pmsapi.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CrossingFilter implements Filter {


private boolean isCross = false;

@Override
public void destroy() {
	isCross = false;
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	if (isCross) {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		System.out.println("拦截请求: " + httpServletRequest.getServletPath());
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
		// httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); // 表示所有请求都有效
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		httpServletResponse.setHeader("Access-Control-Max-Age", "0");
		httpServletResponse.setHeader("Access-Control-Allow-Headers",
				"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
		httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
		httpServletResponse.setHeader("XDomainRequestAllowed", "1");
	}
	chain.doFilter(request, response);
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
	String isCrossStr = filterConfig.getInitParameter("IsCross");
	isCross = isCrossStr.equals("true") ? true : false;
	System.out.println("跨域开启状态:" + isCrossStr);
}

}
<!-- 配置跨域过滤器 -->
<filter>
	<filter-name>CrossingFilter</filter-name>
	<filter-class>com.pmsapi.filter.CrossingFilter</filter-class>
	<init-param>
		<param-name>IsCross</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>CrossingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

获取前端传来的数据

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 1. 从 map 取 前端发过来的 post 数据
//{username=[xxx],password=[xxx],hobby=[eat,drink]}
            Map<String, String[]> parameterMap = req.getParameterMap();
            // 2. 遍历 map 数据 ----> 字符串
            String namePwd = "";
            if (parameterMap != null) {
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    namePwd = entry.getKey();
                    System.out.println(namePwd);
                }
            }
            // 3. 字符串 ----> json
            JSONObject params = JSON.parseObject(namePwd);
            String username = params.getString("username");
            int pwd = params.getInteger("pwd");
}

2.前端的处理   

查看vue版本npm list vue或是在package.json文件里找”dependencies”直接看到

vue2

原理:给url加上了前缀 /api,我们前端发起请求/dev/unit/queryTree访问https://locall/host:8080/dev/unit/queryTree就当于访问了:https://locall/host:8080/api/dev/unit/queryTree

又因为在 index.js 中的 proxyTable 中拦截了 /api ,并把 /api 及其前面的所有替换成了 target 中的内容,因此实际访问 Url 是https://www.wd.com/dev/unit/queryTree。红色是target,绿色是前端发起的具体请求,对应后端的请求

1.vue.main.js  配置访问的url前缀

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import axios from 'axios'//引入axios,来发送请求
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.axios = axios
axios.defaults.timeout = 5000;// 在超时前,所有请求都会等待 5 秒
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8';// 配置请求头
axios.defaults.baseURL = '/api';// 作用是我们每次发送的请求都会带一个/api的前缀。
axios.defaults.withCredentials = false;
new Vue({
    el: '#app',
    components: {App},
    template: '<App/>'
    // render: h => h(App)
})

2.修改config文件夹下的index.js文件,在proxyTable中加上如下代码:  代理,如果没有这部分,那么跨域的路径就是baseurl+具体请求

'/api':{
    target: "https://www.wd.com/dev",
    changeOrigin:true,
    pathRewrite:{
        '^/api':''     //因为本身的请求中没有api,所以去掉,eg:前端请求/api/ser,实际后端:https://www.wd.com/dev/ser
    }
}

3.app.vue

<template>
  <div>
    <el-menu></el-menu>
        <el-table></el-table>
        <br/>
        <el-page></el-page>
  </div>
</template>
<script>
import nav from "./components/NavMenu.vue"
import eletable from "./components/Table.vue"
import pageination from "./components/Pagination.vue"
export default {
  components:{
        ElMenu:nav,
        ElTable:eletable,
        ElPage:pageination
    },
    data(){
        return{}
    },
    methods:{
    },
    mounted() {
            this.axios({
                method: 'get',
                url: '/test/test',
                params: this.urlParams
            }).then((res) => {
                console.log(res)
                console.log(res.data)
                alert(res.data.msg)
            }).catch((err) => {
                console.log(err)
            })
    }
}
</script>

vue3

在config.js中这样写
devServer: {
    open: true, //是否自动弹出浏览器页面
    host: "localhost",
    port: '8080',
    https: false,
    hotOnly: false,
    proxy: //或者直接写上协议 域名 端口号,在请求的时候加上请求和这个拼接上
{
        '/api': {
            target: 'https://www.v2ex.com/api', //API服务器的地址
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
    },
}

3.vue+webpack项目搭建实现前后端交互

1.检查本地环境

  • node -v
  • npm -v
  • vue -V

2.进入目录文件夹创建项目

vue init webpack vue-project-name

3.安装依赖

npm操作: 与cnpm yarn的区别是他们下载源不同,npm会更满=慢些
安装vue-router:
npm install vue-router --save-dev     dev表示生产环境,开发环境不加dev
安装element-ui: 与路由相关的元素上需要加上router,在vue文件中的element元素上,如果表单中某个元素的值是变量,需加上:    ,比如:key="i"
npm i element-ui -S         -S表示plus的意思,不加plus的只支持vue2.几版本,vue3使用plus的
安装SAss加载器:
npm install sass-loader node-sass --save-dev
安装axios:
npm install --save axios vue-axios
注意安装依赖之后要重新执行nmp install

4.启动浏览器进行访问

npm run dev是适用于老版本;新版本使用npm run server

完成后,可在生成的项目中修改基础配置,比如运行监听端口,默认是8080,如果担心有冲突可自行更改,更改文件在config—index.js 。项目基础信息在package.json文件中,有项目名称、作者、运行说明等,可自行查阅,启动项目命令:npm run dev启动完成后回返回请求的地址,复制到浏览器即可请求项目。


5.实现登录

1

  • http是无状态的通过cookie在客户端记录状态通过session在服务器端记录状态通过token方式维持状态
  • 将登录之后的token,保存到客户端的sessionStorage中.项目中除了登录之外的其他API接口,必须在登录之后才能访问;token只应在当前网站打开期间生效,所以将token保存在sessionStorage中

2.Element-UI组件实现布局

  • el-form
  • el-form-item
  • el-input
  • el-button
  • 字体图标

3.Login.vue

<template>
  <div class="login-wrap">
    <el-form class="login-container">
      <h1 class="title">用户登录</h1>
      <el-form-item label="账号">
        <el-input type="password" v-model="uname" placeholder="登录账号" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="登录密码">
        <el-input type="password" v-model="password" placeholder="登录密码" autocomplete="off"></el-input>
      </el-form-item>
 
      <el-form-item>
        <el-button type="primary" style="width: 100%;" @click="dosubmit()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
  export default {
    name: 'login',
    data: function() {
      return {
        uname: "张三",
        password: "123"
      }
    },
    methods: {
      dosubmit: function() {
        let params = {
          uname: this.uname,
          password: this.password
        };
      
      }
    }
  }
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .login-wrap {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding-top: 10%;
    background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjEzNjFweCIgaGVpZ2h0PSI2MDlweCIgdmlld0JveD0iMCAwIDEzNjEgNjA5IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0Ni4yICg0NDQ5NikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+R3JvdXAgMjE8L3RpdGxlPgogICAgPGRlc2M+Q3JlYXRlZCB3aXRoIFNrZXRjaC48L2Rlc2M+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iQW50LURlc2lnbi1Qcm8tMy4wIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0i6LSm5oi35a+G56CB55m75b2VLeagoemqjCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTc5LjAwMDAwMCwgLTgyLjAwMDAwMCkiPgogICAgICAgICAgICA8ZyBpZD0iR3JvdXAtMjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDc3LjAwMDAwMCwgNzMuMDA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3B5LTQiIGZpbGwtb3BhY2l0eT0iMC42IiBmaWxsPSIjRDFERUVEIiBjeD0iMjQzLjgzMzMzMyIgY3k9IjMwLjMzMzMzMzMiIHI9IjUuODMzMzMzMzMiPjwvY2lyY2xlPgogICAgICAgICAgICAgICAgICAgIDxjaXJjbGUgaWQ9Ik92YWwtNS1Db3B5LTUiIGZpbGw9IiNFMEI0QjciIGN4PSIxNzUuNTgzMzMzIiBjeT0iMjMyLjc1IiByPSI1LjI1Ij48L2NpcmNsZT4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+);
    /* background-color: #112346; */
    background-repeat: no-repeat;
    background-position: center right;
    background-size: 100%;
  }
 
  .login-container {
    border-radius: 10px;
    margin: 0px auto;
    width: 350px;
    padding: 30px 35px 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    text-align: left;
    box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
  }
 
  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }
</style>

4.配置路由

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/view/Login'
 
Vue.use(Router)
 
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
  ]
})

5.跨域请求

get:

<script>
import axios from 'axios'
import qs from 'qs'
  export default {
    name: 'login',
    data: function() {
      return {
        uname: "张三",
        password: "123"
      }
    },
    methods: {
      dosubmit: function() {
        let params = {
          uname: this.uname,
          password: this.password
        };
        var url = "http://localhost:8080/ssm02/login";
        axios.get(url, { //注意数据是保存到json对象的params属性
          params: params
        }).then(function(response) {
           console.log(response);
         }).catch(function(error) {
          console.log(error);
        });
        var str=qs.stringify(params);
        axios.post(url,str//注意数据是直接保存到json对象
        ).then(function(response) {
          console.log(response);
        }).catch(function(error) {
          console.log(error);
        });
 
 
      }
    }
  }
</script>

post文章来源地址https://www.toymoban.com/news/detail-400398.html

var str=qs.stringify(params);
        axios.post(url,str//注意数据是直接保存到json对象
        ).then(function(response) {
          console.log(response);
        }).catch(function(error) {
          console.log(error);
        });
  因为POST提交的参数的格式是Request Payload,这样后台取不到数据的(详情见资料“05 Vue中axios踩坑之路-POST传参 - RainSun - CSDN博客.mht”),
           解决方案:使用qs.js库,将{a:'b',c:'d'}转换成'a=b&c=d'

到了这里,关于vue前端与Java后端进行跨域交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 解决前端跨域的几种方法

    一、跨域报错         在我们实际开发过程中,都有遇到过跨域的问题,跨域报错如下: 二、为什么会报跨域?         跨域的本质是浏览器基于同源策略的一种安全手段,主要是考虑到用户的信息安全。何为同源策略呢?同源策略是一种约定,它是浏览器最核心也

    2024年02月09日
    浏览(49)
  • 前端和后端解决跨域问题的方法

    目前很多java web开发都是采用前后端分离框架进行开发,相比于单体项目容易产生跨域问题。  后端接收到请求并返回结果了,浏览器把这个响应拦截了。 浏览器 基于同源策略,如果请求的网页和当前的服务 不是同源的 ,并且发送的是 XHR (XMLHttpRequest)请求,就会产生跨域

    2024年04月26日
    浏览(41)
  • 与iframe进行跨域交互的解决方案

    目录 前言 使用 postMessage() 方法 使用location.hash  document.domain属性  使用window.name 属性  CORS 使用JSONP 使用WebSocket  使用WebRTC  使用中间页面  在Web开发中,为了避免安全漏洞,浏览器会实行同源策略(Same-Origin Policy),即只允许同源网页之间进行交互,而跨域的交互是被禁止

    2024年02月05日
    浏览(44)
  • 前端和后端之间的CORS 跨域和解决办法

            跨源资源共享 (CORS,或通俗地译为跨域资源共享)是一种基于 HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其他源(域、协议或端口),使得浏览器允许这些源访问加载自己的资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送

    2024年01月23日
    浏览(52)
  • vue页面内嵌iframe使用postMessage进行数据交互(postMessage跨域通信)

    什么是postMessage postMessage 是 html5 引入的 API ,它允许来自 不同源 的脚本采用 异步方式进行有效的通信 ,可以实现跨文本文档,多窗口,跨域消息传递.多用于窗口间数据通信,这也使它成为 跨域通信 的一种有效的解决方案. vue父页面(嵌入iframe的页面) 在vue中要使用iframe上的pos

    2023年04月25日
    浏览(61)
  • vue解决跨域的几种办法

    当我们遇到请求后台接口遇到 Access-Control-Allow-Origin 时,那说明跨域了。 跨域是因为浏览器的同源策略所导致,同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,同源是指:域名、协议、端口相同 解决跨域常用方法: 一、VUE中常用proxy来解决跨

    2024年02月15日
    浏览(47)
  • 前端VUE后端JAVA,SM2加解密,一篇解决你的问题

    1、后端加密后密文前两位为“04”,前端解密不了,所以在前端解密时要把“04”去掉, 2、前端加密后,密文没有“04”,所以前端加密完要在密文前面加上“04”

    2024年04月23日
    浏览(38)
  • 前端调用DRI后端API出现跨域资源共享(CORS)问题解决办法

    目录 1. 引言 2. 跨源资源共享和实现方法 3. 在Django项目中配置django-cors-headers库 Reference 在进行后端API开发时,有时会遇到“跨域资源共享 (CORS) 请求...被阻止“的错误,如图1所示。本文讲解如何在使用DRF(Django REST Framework)的后端API开发项目中解决这个问题。 A cross-origin re

    2024年04月25日
    浏览(51)
  • vue如何解决跨域的问题,有哪几种方式?

    在使用axios发送请求之后,没有得到返回的数据,打开控制台发现如下图所示的报错: 这是提示跨域了。所有使用JavaScript的浏览器都会支持同源策略。同源策略即指域名/协议/端口号相同。只要有一个不同,就会当作跨域请求。  解决方法为: 1. CORS 后端通过 CORS 解决跨域

    2024年02月08日
    浏览(69)
  • 已配置vue.config.js中的proxy代理,前端本地环境仍然请求后端出现跨域报错

    已配置vue.config.js中的proxy代理,前端本地环境仍然请求后端出现跨域报错 已配置vue.config.js中的proxy代理,前端本地环境仍然请求后端出现跨域报错 控制台仍然出现cors禁止报错,接口调不通 配置proxy代理解决跨域问题的原理是: 前端工程本地环境会启动一个 express 或 koa 的

    2024年02月01日
    浏览(56)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包