首页
Javascript
Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

nginx优化跨域的OPTIONS请求

2020年03月07日 发布 阅读(7652) 作者:Jerman

什么情况下会有OPTIONS请求

1、跨域
2、自定义请求头或请求头中的content-type是application/x-www-form-urlencoded,multipart/form-data,text/plain之外的格式

满足上面两点,浏览器就会在发送数据请求之前,先发送OPTIONS请求。

那跨域的项目,每次请求都会先发送OPTIONS请求,是不是很浪费宽带?影响性能?怎么优化?

OPTIONS优化

我们可以在nginx或后台项目中设置Access-Control-Max-Age属性(单位为秒),以减少OPTIONS请求

在不同的浏览器中,Access-Control-Max-Age的值会有所不一样,firefox中为24小时 (即86400秒),chrome中为10分钟(即600秒)

如果Access-Control-Max-Age设置为-1,则表示禁用缓存,每次都会在发送数据请求前,发送preflight(即OPTIONS请求)

设置Access-Control-Max-Age,并不代表全局就不发送OPTIONS请求了,它是针对具体请求的一个局部属性,当设置Access-Control-Max-Age后,我们请求/user/info时,第一次还会发送OPTIONS请求的,但第二次请求/user/info时就不会发送OPTIONS请求了,这就达到了优化的目的

代码

贴一段nginx代码吧

  1. location / {
  2. if ($request_method = 'OPTIONS') {
  3. add_header 'Access-Control-Allow-Origin' "http://test.imqianduan.com";
  4. add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
  5. add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  6. add_header 'Access-Control-Allow-Credentials' true;
  7. add_header 'Access-Control-Max-Age' 86400;
  8. return 200;
  9. }
  10. add_header 'Access-Control-Allow-Origin' "http://test.imqianduan.com";
  11. add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
  12. add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  13. add_header 'Access-Control-Allow-Credentials' true;
  14. add_header 'Access-Control-Max-Age' 86400;
  15. proxy_pass http://127.0.0.1:7001;
  16. proxy_set_header Access-Control-Max-Age 86400;
  17. proxy_set_header Host $host;
  18. proxy_redirect off;
  19. proxy_set_header X-Real-IP $remote_addr;
  20. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  21. proxy_connect_timeout 60;
  22. proxy_read_timeout 60;
  23. proxy_send_timeout 60;
  24. }

参考:

MDN: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Max-Age

版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处