vue前端、java后端、nginx三端配置跨域

1. Vue前端配置跨域

1.在vue.config.js文件(修改之后进行重启才有效)或index.js文件中配置

module.exports = {
    devServer: {
        // proxyTable: proxyConfig.proxyList, // 无效,不使用,20190422
        proxy: {
            '/api': {
                target: 'https://c.y.qq.com',//后端接口地址
                changeOrigin: true,//是否允许跨越
                pathRewrite: {
                    '/api': ''
                    //'^/api': '/api',//重写,
                }
            }
        },
    },
}

2. java后端配置跨域

  1. 若没有引入spring security,直接在Controller层上加上CrossOrigin注解即可。
@CrossOrigin
public class UserController {
}

2.若引入了spring security

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(CorsConfigurationSource()).and()//允许跨域
        ;
    }

    private CorsConfigurationSource CorsConfigurationSource() {
        CorsConfigurationSource source =   new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");	//同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
        corsConfiguration.addAllowedHeader("*");//header,允许哪些header,本案中使用的是token,此处可将*替换为token;
        corsConfiguration.addAllowedMethod("*");	//允许的请求方法,PSOT、GET等
        ((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**",corsConfiguration); //配置允许跨域访问的url
        return source;
    }
}

3. nginx配置跨域

	server {
        listen       80;
        server_name  netease.flaming.com;
		add_header Access‐Control‐Allow‐Origin *;
		#允许客户端携带整数访问
		add_header Access‐Control‐Allow‐Credentials true;
		#允许客户端跨域访问的方法
		add_header Access‐Control‐Allow‐Methods GET;

        location / {
			proxy_pass http://192.168.0.135:3000;
			proxy_connect_timeout 600;
			proxy_read_timeout 600;
        }
    }
Logo

前往低代码交流专区

更多推荐