0.什么是跨域

        浏览器的同源策略会阻止从一个加载的脚本去获取另一个域上的文档属性。凡是发送请求url的协议(https协议访问http协议)、域名(包括子域名)、端口(80端口访问8080端口)三者之间任意一个与当前页面地址不同即为跨域。

1.使用CROS解决跨域问题

        JSONP只支持GET请求方式,而CROS除了GET请求方式外也支持其他的HTTP请求。CROS允许浏览器发送XMLHttpRequest请求,从而克服Ajax只能同源请求的问题。
浏览器发出CORS请求,需要对请求头增加一些信息,服务器会根据这些信息来是否决定同意这次请求。请求头信息要在后台设置。需要的头信息字段如下:
        (1)Access-Control-Allow-Origin
         这个头信息字段是必须的。它指定允许进入来源的域名、ip+端口号 。 如果值是 ‘*’ ,表示接受任意的域名请求,这个方式不推荐,主要是因为其不安全,而且因为如果浏览器的请求携带了cookie信息,会发生下图错误。
在这里插入图片描述
         (2) Access-Control-Allow-Credentials
          该字段是可选的。它设置是否可以允许发送cookie,true表示cookie包含在请求中,false则相反,默认为false。如果项目需要cookie就得设置该字段了。CORS请求默认不发送Cookie和HTTP认证信息的,所以在此基础上同时也需要在前端设置(以axios为例): axios.defaults.withCredentials = true
         (3)Access-Control-Max-Age
         该字段是可选的。用于配置CORS缓存时间,即本次请求的有效期,单位为秒。
          (4)Access-Control-Allow-Methods
          该字段可选。设置允许的请求方法。
         (5)Access-Control-Allow-Headers
          该字段可选。设置允许的请求头信息
         (…)其他请参考相关资料
         对于axios,它是vue2提倡使用的轻量版的ajax。它是基于promise的HTTP库。它会从浏览器中创建XMLHttpRequests。

2.配置

2.1 在组件中配置axios

         在发送请求的组件中进行如下的配置

<template>
  <p>this is test Vue</p>
</template>

<script>
    import axios from 'axios'

    // 如果要跨域的话,对axios进行一些设置
    const axiosInstance = axios.create({
        headers:{'Content-Type':'application/json;charset=utf-8'},    // 设置传输内容的类型和编码
        withCredentials:true      // 指定某个请求应该发送凭据  
    });

    export default {
        name: "testAxios",

        mounted() {
            axiosInstance.get('/api/sayHello.do').then((response)=>{
                console.info(response)
            }).catch(error=>{
                console.info(error)
            })
        }
    }
</script>

<style scoped>

</style>
2.2 配置代理

        对config\index.js中ProxyTable部分的数据进行如下的修改。

    proxyTable: {
      '/api': {
        target:'http://127.0.0.1:8081',
        // secure: false, // 如果是https接口,需要配置这个参数
        changeOrigin:true,
        pathRewrite:{
          '^/api': ''
        }
      }
    }
2.3 服务器的拦截器配置

        使用spring MVC 的HandlerIntercAdapter拦截器适配器

public class RquestInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        httpServletResponse.setHeader("X-Powered-By","Jetty");

        String method= httpServletRequest.getMethod();
        if (method.equals("OPTIONS")){
            httpServletResponse.setStatus(200);
            return false;
        }
        System.out.println(method);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}

        然后在Spring MVC的配置文件中添加如下代码。

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="RquestInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

        之后便可以实现从Vue项目的8080端口向8081端口发请求。

3. 测试

        编辑简单的后台接收代码。

@Controller
public class SayHelloController {
    @ResponseBody
    @RequestMapping(value = "/sayHello")
    public String sayHello(){
        return "Hello!";
    }
}

        查看调试窗口的请求结果,请求被正确接收及响应。
在这里插入图片描述
        查看响应结果。
在这里插入图片描述

巨人

https://blog.csdn.net/xshsjl/article/details/82998470
https://blog.csdn.net/github_33809414/article/details/81774885

Logo

前往低代码交流专区

更多推荐