Austin Gayler
Austin Gayler

Reputation: 4376

Trouble getting CORS to work between CodeIgniter and React app

I'm having trouble getting my React app communicating with an API I'm hosting on my computer. I'm not familiar with CodeIgniter too much, so it would be safe to assume errors/misunderstandings on that part. I've tried adding header('Access-Control-Allow-Origin:*'); to the top of application/config/rest.php as well as some other files. When I do an api request, a pre-flight OPTIONS request is apparently first sent, which looks like:

Request Headers:
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: apikey
Origin: http://localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response Headers:
Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: close
Content-Type: text/html; charset=UTF-8
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Host: localhost:8000
Pragma: no-cache
Set-Cookie: ci_session=3ba4cibif5sdgtfjjopmokt8k2fc1c1j; expires=Fri, 24-Feb-2017 19:18:05 GMT; Max-Age=7200; path=/; HttpOnly
X-Powered-By: PHP/5.5.38

The OPTIONS response is 200. On the server, the API seeds the resource I am trying to get and responds with 200 (however my application does not see this). The react front-end sees and logs a super unhelpful

Error: Network Error
Stack trace:
createError@http://localhost:3000/bundle.js line 4801 > eval:15:15
handleError@http://localhost:3000/bundle.js line 4789 > eval:87:14

error and my application never even does the GET request (according to Firefox's dev tools). The OPTION's response's data is completely empty. What is going on here?

Upvotes: 4

Views: 2655

Answers (1)

Austin Gayler
Austin Gayler

Reputation: 4376

Turns out I needed to check if it was a preflight request on the server, and respond appropriately:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
    die();
}

Then I can make normal requests using the api key in my header.

from https://stackoverflow.com/a/19310265/419194

Upvotes: 3

Related Questions