Trong CodeIgniter 3, lỗi CORS (Cross-Origin Resource Sharing) thường xảy ra khi ứng dụng cố gắng lấy dữ liệu từ một API nằm ở domain khác nhưng server không cho phép truy cập từ nguồn gốc đó. Khi gặp lỗi này, trình duyệt sẽ chặn request và không thể lấy được dữ liệu từ API. Nguyên nhân thường là do thiếu header Access-Control-Allow-Origin
hoặc cấu hình sai trong file .htaccess
hoặc controller. Để khắc phục, cần thiết lập đúng các CORS headers trong response của API hoặc cấu hình thêm middleware xử lý CORS.
Khi dùng axios để lấy dữ liệu từ API trên sever sử dụng codeiginiter 3 thì ta thêm đoạn code này vào đầu class
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Chúc bạn thành công