zoukankan      html  css  js  c++  java
  • vue项目解决axios跨域问题

    vue项目解决axios跨域问题

    1、在项目根目录新建vue.config.js文件

    新版本的vuecli已经不会默认添加vue.config.js文件,需要手动创建。

    2、编辑vue.config.js

    将以下文件添加至vue.config.js中

    module.exports = {
      devServer: {
        host: '0.0.0.0',
        open: true,
        proxy: {
          // detail: https://cli.vuejs.org/config/#devserver-proxy
          '/api': {
            target: `http://localhost:18080/`,
            changeOrigin: true,
            pathRewrite: {
              '^/api': ''
            }
          }
        },
        disableHostCheck: true
      }
    }
    

    3、效果

    • 所有以/api开头的请求都会默认访问http://localhost:18080/,虽然浏览器中显示的还是localhost:前端端口/api/xx,但是真正访问的其实是http://localhsot:18080/xx

    • 如果想保留/api,可以在pathRewrite'^/api': ''修改为'^/api': '/api'

    • 如果想代理所有请求,可以将proxy内的'/api'修改为/,将pathRewrite内的'^/api': ''修改为'^/': ''

    Java代码解决跨域

    增加以下配置类

    package cn.xxx.xxx.xxx;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    /** 跨域配置 */
    @Configuration
    public class CorsConfig {
      private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1 设置访问源地址
        corsConfiguration.addAllowedOrigin("*");
        // 2 设置访问源请求头
        corsConfiguration.addAllowedHeader("*");
        // 3 设置访问源请求方法
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
      }
    
      @Bean
      public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 4 对接口配置跨域设置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
      }
    }
    
    
  • 相关阅读:
    ulimit -a
    nginx check_http_send type=http 查检测不到后端TOM的存活
    通过ip查找能应机器的MAC
    错误状态码URL重定向
    error_page 改变状态码为新的状态码,并显示指定内容
    使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器
    C#客户端嵌入Chrome浏览器的实现
    Task.Run c#启动线程
    C#利用webBrowser怎么去掉网页中不想显示的部分
    InDesign CC 2019安装包+破解
  • 原文地址:https://www.cnblogs.com/zhangruifeng/p/15625238.html
Copyright © 2011-2022 走看看