Saturday, December 31, 2016

react.js with PHP, cookies/CORS/session id etc

I am working on a react.js app on my Windows machine. Dev server is running on http://localhost:3000. While connection to my backend PHP server at, I ran into multiple issues related to CORS - Cross Origin Resource Sharing

Here are some problems and solution

If you want everything to work smoothly, do this
In your PHP code, add this:

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");

or in your .htaccess file add this:
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true

and while sending requests from react.js, for which I was using fetch API, in every request add credentials: 'include'
fetch(',{credentials: 'include'}).then(function (response) {
return response.json()
}).then(function (resp) {
that.setState({blogList: resp})
Another solution is to run Chrome like this: (this will disable CORS checks)
chrome.exe --disable-web-security --user-data-dir=c:\mydata

Another error message you may get depending upon your code/config is this: (but the above solution is perfect)
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
Another error you might encounter is this:(Even this problem will disappear if you follow the first solution)
1. PHP is sending PHPSESSID as a response cookie in your first request
2. But your next request is not using that cookie as a request cookie, or is using a different PHPSESSID

No comments:

Blog Archive