How to fix Access-Control-Allow-Origin

Access to fetch at ‘http://127.0.0.1:3001/movies’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

ปัญหาเกิดจาก client พยายามจะเรียก web server ข้าม domain กัน ทำให้เกิดปัญหา Access-Control-Allow-Origin

วิธีแก้แบบแรกก็ลง Extension ที่ chrome ชื่อ Moesif Orign & CORS Changer

กดปิดแม่ม แค่นี้ data ก็มาละ

แต่มันเป็นการแก้ปัญหาที่ปลายเหตุ เราไปทำที่ code เราดีกว่า นะ นะ นะ

NodeJS

router.get('/', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true); 
});

php

<?php 
header('Access-Control-Allow-Origin: *');
?>

แถมๆ หรือจะไปใส่เพิ่มที่ Web Server

nginx ไปแก้ที่ nginx.conf

server {
    ...

    location / {
        proxy_pass   http://127.0.0.1:8080;
        add_header   Access-Control-Allow-Origin *;
    }   
}

Apache แก้ที่ .htaccess

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
(Visited 1,544 times, 1 visits today)
Spread the love