nginx解决跨域问题!

1、问题背景:前端调用线上后段时出现跨域问题!

解决方法nginx的location头部增加配置:

                 add_header 'Access-Control-Allow-Headers' '*';
                 add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,HEAD,PUT';
                 add_header 'Access-Control-Allow-Origin' '*';
                 add_header 'Access-Control-Allow-Credentials' 'true'

本地前端调用php接口时需在后端的 location字段都加配置。

2、当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource,需要给Nginx服务器配置响应的header参数:

解决方案:

location / {  
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
  add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
} 

3、Ajax跨域请求保证同一个session的问题

我们知道,根据浏览器的保护规则,跨域的时候我们创建的sessionId是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的sessionId就不会被保存下来,也就是说,每一次的请求,服务器就会以为是一个新的人,而不是同一个人,为了解决这样的办法,下面这种方法可以解决这种跨域的办法。

我们自己构建一个拦截器,对需要跨域访问的request头部重写:

       add_header Access-Control-Allow-Origin "$http_origin";
       add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
       add_header Access-Control-Allow-Headers  "Origin, Accept, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token";
       add_header Access-Control-Allow-Credentials "true";

猜你喜欢

转载自blog.csdn.net/weixin_42207486/article/details/82494638