zoukankan      html  css  js  c++  java
  • 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/;
    }
    
    
  • 相关阅读:
    用js onselectstart事件鼠标禁止选中文字
    模仿苹果菜单的导航
    返回页面顶部
    商品展示的放大镜效果
    键盘控制Div的移动
    Div跟随鼠标移动
    瀑布流的布局(功能还没有完善)
    类似时光轴的效果
    ie6-ie8中不支持opacity透明度的解决方法
    :active pseudo-class doesn't work in mobile safari
  • 原文地址:https://www.cnblogs.com/jone-chen/p/13602799.html
Copyright © 2011-2022 走看看