แก้ปัญหา เขียน javascript หรือ angular ฯลฯ แล้วติด CORS

ปัญหานี้จะพบเมื่อเราทำการส่ง request แบบ cors วิธีแก้นั้นมีอยู่หลักๆ ก็ 3 วิธี
  1. ทำ Reverse proxy ไปยัง server ปลายทาง
  2. แก้ที่ server ให้ส่ง header cors กับมาด้วยเมื่อได้รับ request OPTIONS
  3. ใช้ JSONP

ซึ่งวิธีที่ 2,3 เนี่ยเราจะทำไม่ได้ถ้าเราไม่มีสิทธิ์แตะต้องเครื่อง server

วิธีที่ผมจะบอกต่อไปนี้สามารถใช้ได้กับ 1 และ 2 แต่เป็นวิธีสำหรับ  nginx นะ
จากหลักการก็คือถ้าเราจะทำการ request CORS แล้วล่ะก็ browser จะทำการส่ง request HTTP OPTIONS ไปก่อน แล้วอ่าน header ที่ได้กลับมาว่าอนุญาติให้ CORS ไหม อนุญาติ Method ไหนบ้าง ฉะนั้นสิ่งที่เราจะทำก็คือเพิ่มส่วนที่ว่านั้นเข้าไป
location / {
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        #
        
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        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 = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }
     #########################
     ### YOUR OTHER CONFIG ###
     ###       HERE        ###
}

คำอธิบายเพิ่มเติม : ตาม config เลยครับ น่าจะเข้าใจไม่ยาก :3
ทดสอบแบบง่ายโดยการใช้ curl ไปที่ url ดังกล่าว
curl -X OPTIONS -i https://myapi/api
สังเกตุบริเวณ http header จะเห็นว่ามีพวก Access-Control-Allow-Origin  และอื่นๆตอบกลับมาแล้ว เป็นอันว่าใช้ได้ :=
จาก : http://enable-cors.org/server_nginx.html

Comments