Skip to content
Advertisement

CORS issue in codeigniter 4: Response to preflight request doesn’t pass access control check

I’m making an api with Codeigniter 4 for a react application. Everything works fine in postman but when I make requests with axios (also tried fetch), it gets CORS error

Access to XMLHttpRequest at ‘http://localhost:8080/testpost‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I tried adding headers to base controller:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST,GET, OPTIONS");
header("Access-Control-Allow-Headers: *");

Now it works fine with requests without JSON body, but when I send json body same error occurs.

axios.post("http://localhost:8080/testpost", { data: "test" })
    .then((response) => {
        console.log(response);
    })
    .catch((err) => {
        console.log("error!!!");
    });
// Routes.php
$routes->post('/testpost', 'Home::testPost');
// Home Controller
public function testPost()
{
    return $this->response->setJSON('test response');
}

Thanks for your help

Advertisement

Answer

Please try by setting Apache response headers and redirect method to .htaccess in root of www/public directory, like this:

#Redirect for CORS Preflight request
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
#Set headers to access CORS Requests / allowing localhost only
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

NOTE: Be careful by adding Header always add Access-Control-Allow-Origin "*" to your .htaccess, "*" open doors for attackers, replace * with your domain or subdumain!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement