M
M
moow2021-10-17 04:54:55
PHP
moow, 2021-10-17 04:54:55

How to enable CORS in php and get data via ES6 from another domain?

I configured the server, it issues such headers:

HTTP/1.1 200 OK 
Date: Sun, 17 Oct 2021 01:38:17 GMT 
Server: Apache/2.4.29 (Ubuntu) 
Strict-Transport-Security: max-age=31536000; preload 
Expires: Thu, 19 Nov 1981 08:52:00 GMT 
Cache-Control: no-store, no-cache, must-revalidate, max-age=0 
Pragma: no-cache 
Access-Control-Allow-Origin: * 
Access-Control-Allow-Methods: * 
Access-Control-Allow-Headers: * 
Access-Control-Allow-Credentials: true 
Cache-Control: post-check=0, pre-check=0 
Content-Length: 13 
Keep-Alive: timeout=5, max=100 
Connection: Keep-Alive 
Content-Type: application/json; charset=utf-8


When I try to get the content of the response from the server from the client, I get an error in the console:

Access to fetch at '______' from origin 'http://0.0.0.0:9000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


Here is the client code
fetch(url, {
    headers: { "Content-Type": "application/json; charset=utf-8" },
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    body: JSON.stringify(data),
}).then(res => res.json())
    .then(response => {
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    });


What am I missing?

I noticed that the client still sends a request using the OPTIONS method. I don’t know what it is and why, but my server responds to this request with a 404 error. How to process it and is it necessary?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-10-17
@zkrvndm

Yes need. The OPTIONS request is a pre-request, your browser sends it to see what headers are worth and only if there are permission headers it will send the second real request.
Reconfigure your server to return the same headers instead of 404, but without the request body.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question