ÔõÑùʵÏÖNginxµÄ¿çÓò×ÊÔ´¹²Ïí£¨CORS£©ÉèÖÃ
ÔõÑùʵÏÖNginxµÄ¿çÓò×ÊÔ´¹²Ïí£¨CORS£©ÉèÖã¬ÐèÒªÏêϸ´úÂëʾÀý
Ëæ×ÅÇ°ºó¶ËÊèÉ¢¿ª·¢µÄÊ¢ÐУ¬¿çÓò×ÊÔ´¹²Ïí£¨CORS£©ÎÊÌâ³ÉΪÁËÒ»¸ö³£¼ûµÄÌôÕ½¡£ÔÚWeb¿ª·¢ÖУ¬ÓÉÓÚä¯ÀÀÆ÷µÄͬԴսÂÔÏÞÖÆ£¬¿Í»§¶ËJavaScript´úÂëÖ»ÄÜÇëÇóÓëÆäËùÔÚÒ³Ãæ¾ßÓÐÏàͬÓòÃû¡¢ÐæźͶ˿ڵÄ×ÊÔ´¡£È»¶ø£¬ÔÚÏÖʵ¿ª·¢ÖУ¬ÎÒÃǾ³£ÐèÒª´Ó²î±ðÓòÃû¡¢»òÕßÊDzî±ð×ÓÓòÃûÏÂÇëÇó×ÊÔ´¡£Õâʱ¼ä£¬¾ÍÐèҪʹÓÃCORSÀ´½â¾ö¿çÓòÎÊÌâ¡£
NginxÊÇÒ»¸ö¹¦Ð§Ç¿Ê¢µÄ¿ªÔ´WebЧÀÍÆ÷Èí¼þ£¬¿ÉÒÔÉèÖóɷ´ÏòÊðÀíЧÀÍÆ÷£¬ÓÃÓÚÌṩ¾²Ì¬×ÊÔ´¼°ÊðÀíÇëÇó¡£ÔÚNginxÖÐʵÏÖCORSÉèÖ㬿ÉÒÔ½â¾öÇ°¶Ë¿çÓòÎÊÌâ¡£ÏÂÃ棬ÏêϸÏÈÈÝÔõÑùÔÚNginxÖÐÉèÖÃʵÏÖCORS¡£
Ê×ÏÈ£¬ÔÚNginxÉèÖÃÎļþÖÐÌí¼ÓÒÔÏ´úÂë¿é£º
location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; } }
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂëÖУ¬ÎÒÃÇʹÓÃadd_headerÖ¸ÁîÀ´ÉèÖÃÏìӦͷÐÅÏ¢£¬ÊµÏÖCORSÉèÖá£ÏêϸÀ´Ëµ£¬ÉèÖÃÁËAccess-Control-Allow-OriginͷΪ*£¬ÌåÏÖÔÊÐíËùÓÐȪԴ¡£È»ºó£¬ÎÒÃÇÉèÖÃÁËAccess-Control-Allow-MethodsÍ·£¬ÔÊÐíÇëÇóÒªÁìΪGET¡¢POSTºÍOPTIONS¡£½ÓÏÂÀ´£¬ÎªÁËÖ§³ÖcontentTypeΪapplication/jsonµÈÃûÌõÄÇëÇó£¬ÎÒÃÇÉèÖÃÁËAccess-Control-Allow-HeadersÍ·¡£×îºó£¬ÎÒÃÇʹÓÃAccess-Control-Expose-HeadersÍ·À´ÉèÖÃЧÀÍÆ÷¿ÉÒÔ·µ»ØµÄÇëÇóÍ·¡£
½ÓÏÂÀ´£¬ÖØÐÂÆô¶¯NginxЧÀÍÆ÷£¬Ê¹ÉèÖÃÉúЧ¡£
ÉèÖÃÍê³Éºó£¬Nginx»áƾ֤ÉèÖõÄÏìӦͷÐÅÏ¢£¬ÔÚÏìÓ¦ÖÐÌí¼ÓCORSÏà¹ØµÄÍ·²¿ÐÅÏ¢¡£ÕâÑù£¬µ±ä¯ÀÀÆ÷Ìᳫ¿çÓòÇëÇóʱ£¬Ð§ÀÍÆ÷»á·µ»ØÕâЩͷ²¿ÐÅÏ¢£¬ä¯ÀÀÆ÷¾ÍÄÜÕý³£´¦Àí¿çÓòÇëÇóÁË¡£
ÐèҪעÖصÄÊÇ£¬ÓÉÓÚCORSÉèÖõĿª·ÅÐÔ£¬¿ÉÄܱ£´æÇ徲Σº¦¡£ÈôÊÇÓÐÐëÒª£¬¿ÉÒÔƾ֤ÏêϸµÄÓªÒµÐèÇó£¬ÏÞÖÆAccess-Control-Allow-OriginÍ·µÄֵΪÕýµ±µÄÓòÃû¡£ÕâÑù£¬Ö»ÓÐÖ¸¶¨µÄÓòÃû²Å»ª¿çÓòÇëÇóЧÀÍÆ÷×ÊÔ´¡£
×ÛÉÏËùÊö£¬Ê¹ÓÃNginxÉèÖÃCORS¿ÉÒԺܺõؽâ¾öÇ°¶Ë¿çÓòÎÊÌ⡣ͨ¹ýÉèÖÃÏìÓ¦µÄÏìӦͷÐÅÏ¢£¬ÎÒÃÇ¿ÉÒÔʵÏÖ¸üÎÞаµÄ¿çÓò×ÊÔ´¹²Ïí¡£Ï£Íû±¾ÆªÎÄÕÂÄܶÔÄãÓÐËù×ÊÖú£¬ÏíÊÜÎÞ¿çÓò¿ª·¢µÄ¿ìÀÖ£¡
ÒÔÉϾÍÊÇÔõÑùʵÏÖNginxµÄ¿çÓò×ÊÔ´¹²Ïí£¨CORS£©ÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡