ngix配置前端跨域问题

当前端请示后端接口的时候,request请求头如果默认是application/json的时候,在浏览器会发现,明明post请求,为何变成了options(options请求是预请求,post的application/json其实是两次请求,预请求如果被服务器拒绝,就不再执行了),并且会提示跨域错误,这个时候解决的方法有三种:
第一种、后端设置允许跨域,以java spirngboot为例,可以这么设置:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE","OPTIONS","HEAD"};

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods(ORIGINS).maxAge(3600).allowCredentials(true);
    }
}

第二种、前端vue/react工程可以设置proxy代理(webpack代理)例:

proxy: {
    '^/api': {
        target: 'http://192.168.4.189:8085/bigdata-ltyfk',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        }
    },
}

第三种、ngix允许跨域

location ^~ /yihao01-lty5.0-vram-web/ {
    add_header 'Access-Control-Allow-Origin' "*";
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,DELETE';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token';
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' "*";
	add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,DELETE';
	add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token';
	add_header 'Content-Type' 'text/plain; charset=utf-8';
	add_header 'Content-Length' 0;
	return 200;
    }
    proxy_pass http://192.168.0.31:7777/;
}

posted @ 2020-09-02 17:14  Jone_chen  阅读(132)  评论(0编辑  收藏  举报