I am working on creating a bulletin board system with PHP backend as an API and React for the frontend that makes requests to the PHP API for data.
In my PHP code, in my CoreMiddleware class:
/**
* Middleware for handling CORS.
*
* @param Request $request the request object
* @param callable $next the next middleware to execute
* @return void
*/
public function handle(Request $request, callable $next) {
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 86400');
header('Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;
return $next($request);
}
I have set all the headers for CORS. When React makes a request to the PHP API, no COR headers are sent. See the snapshot from the network information in chrome:
React Network Snapshot
Now if I access the API directly in a web browser, I get the COR headers. See the snapshot below:
PHP API accessed directly in chrome snapshot
And below is the React code for requesting data from the API:
/**
* Constructor that sets up this class.
*/
constructor() {
this.apiBaseUrl = process.env.REACT_APP_API_BASE_URL;
console.log(process.env);
this.client = axios.create({
baseURL: this.apiBaseUrl,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true
});
}
/**
* Gets data from the API.
* @param {string} endpoint the API endpoint
*/
getData(endpoint) {
return this.client.get(endpoint)
.then(response => response.data)
.catch(error => this.handleError(error));
}
How can I get the COR headers to send when React makes a request to the PHP API? I rarely ever ask questions on here, but I can’t seem to figure it out for the life of me.
I tried adding the CORS headers into the .htaccess file, the apache config file, directly through PHP. After that I expected the COR header issue to be resolved.
Sam Wilcox is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
GET requests from the client do not always need the Access-Control-Allow-Credentials header. This header is needed only in certain specific cases:
When you are making a request with credentials (such as cookies, HTTP authentication, or TLS client certificates): In this case, you need to make sure that the server also includes the Access-Control-Allow-Credentials: true header.
Also, the Access-Control-Allow-Origin header cannot have an asterisk (*); it must be a specific origin.
For simple, non-credential requests: You do not need the Access-Control-Allow-Credentials header.
Just make sure that the server allows the request via the Access-Control-Allow-Origin header.
Access-Control-Allow-Credentials
2