ถ้าคุณติด CORS เราคือเพื่อนกัน
เชื่อว่า Web Developer หลายคนติดปัญหานี้ แน่นอน วันนี้ก็จะมาขยายความเรื่อง CORS จากบทความก่อนหน้านี้
ความเดิมตอนที่แล้ว
Cross-Origin Resource Sharing (CORS)
เป็นกลไกที่ใช้ HTTP headers เพิ่มเติมเพื่อให้บราวเซอร์ได้รับสิทธิ์ในการเข้าถึงทรัพยากรที่เลือกจากเซิร์ฟเวอร์บนโดเมนอื่นมาแสดงบนหน้าเว็บบราวเซอร์ได้ ด้วยเหตุผลเรื่องความปลอดภัยของ Browsers HTTP การอนุญาตให้เข้าถึงแหล่งข้อมูลจะต้องอยู่โดเมนเดียวกันเท่านั้น สามารถแก้ไขได้ โดยให้แหล่งข้อมูล อนุญาตให้โดเมนของ Browsers สามารถเข้าถึงข้อมูลได้
ถ้าเจอข้อความข้างบนนี้ทำไงดี
- สร้าง Project
mkdir express-cors //สร้าง project
cd express-cors //เข้า projectnpm init -y //สร้าง initial package.jsonnpm install express
2. Allow Origin
มากำหนด CORS กัน ใน express กัน copy code ด้านล่างนี้ ไปวางไว้ใน server.js
line 5 กำหนด อนุญาตให้ http://localhost:3000 เข้าถึงข้อมูลได้
line 6 กำหนด อนุญาติ method ที่สามารถยิงเข้ามาได้
line 10 กำหนด api post
line 11 กำหนด api get
จริงๆกำหนดแค่นี้ก็ได้ หาก front-end ไม่มีการส่ง headers เข้ามา ตัวอย่างเช่น
แบบนี้ไม่ติด CORS
axios.get(“http://localhost:5000/foo")
แบบนี้ติด CORS
axios.post(“http://localhost:5000/foo") เพราะว่า method post จะแนบ headers ที่ชื่อว่า Content-Type ไปด้วย ใน code เรายังไม่ได้ Allow headers Content-Type
3. Allow Headers
ทีนี้มากำหนด Headers กัน
line 7 กำหนด อนุญาตให้ ส่ง Headers Content-Type, Option, Authorization เข้ามาได้
4. Run server
node server.js
ข้อควรระวัง
การกำหนด Origin
การกำหนด Headers
Error Cors
- Reason: CORS disabled
- Reason: CORS request did not succeed
- Reason: CORS header ‘Origin’ cannot be added
- Reason: CORS request external redirect not allowed
- Reason: CORS request not http
- Reason: CORS header ‘Access-Control-Allow-Origin’ missing
- Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘xyz’
- Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’
- Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’
- Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’
- Reason: CORS preflight channel did not succeed
- Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’
- Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’
- Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel
- Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed
อ้างอิง
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS