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/;
    }
    
    
  • 相关阅读:
    Nginx安装
    win卸载输入法之后,在系统设置的键盘中还有这个输入法
    为Delphi 10.4.2实现android拍照填坑
    图文解说 ChinaCock 华为扫描
    Delphi Event Bus进阶(二)GlobalEventBus是怎么来的?
    小心SecondsBetween有坑
    Delphi Event Bus进阶(一)控制订阅方法的线程模式
    Delphi 10.4.2试用报告
    Delphi Event Bus入门
    UML建模——活动图(Activity Diagram)
  • 原文地址:https://www.cnblogs.com/jone-chen/p/13602799.html
Copyright © 2011-2022 走看看