记录一次前端vue对接后端springboot遇到的跨域问题解决

spring端参考:

springmvc或者springboot 中实现跨域的5种方式_T-OPEN的博客-CSDN博客

我用的是这个方法:

package com.mesnac.aop;

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.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}

vue端官方有相关文档:配置参考 | Vue CLI (vuejs.org)

他的代码注释多(哈哈哈):Vue2 - 配置跨域 - 武卡卡 - 博客园 (cnblogs.com)

我的代码:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    open: true,
    host: 'localhost',
    port: 8000,
    proxy: {
      '/abc': {    //1
        target: 'https://www.baidu.com',    //2
        changOrigin: true,
        pathRewrite: {    //3
          '^/abc': ''
        }
      },
      // '/lzy': 为这个url起个名字
      '/lzy': {
        // 名字对应的地址
        target: 'http://rjk.zhexin.fun:10013',
        // 开启跨域
        changeOrigin: true,
        pathRewrite: {
          // 当我使用 '^/lzy':自动改成/v1,这里名为代理,例如:
          //http://rjk.zhexin.fun:10013/lzy/ss?a=1  自动改成:  http://rjk.zhexin.fun:10013/v1/ss?a=1
          '^/lzy': '/v1'
        }
      }

    }
  }
})

然后使用案例:用的axios:

mounted() {

        var config = {
            method: 'get',
            // /lzy就可以自动导航到http://rjk.zhexin.fun:10013/lzy  然后通过代理改成: http://rjk.zhexin.fun:10013/v1
            //所以这里的url其实是: http://rjk.zhexin.fun:10013/v1/library/getdata?pageSize=10&pageNo=2&nameAllFuzzy=%E5%A4%A7%E5%B8%88'
            url: '/lzy/library/getdata?pageSize=10&pageNo=2&nameAllFuzzy=%E5%A4%A7%E5%B8%88',
            headers: {
                'time': '1700622053324',
            }
        };

        axios(config)
            .then(function (response) { //访问成功
                console.log(JSON.stringify(response.data));
            })
            .catch(function (error) {  //发生错误
                console.log(error);
            });
    },

 

posted @ 2023-11-24 09:23  哲_心  阅读(65)  评论(0编辑  收藏  举报