I am making a chat application using PHP on backend and React.js on frontend. However, I am encountering a problem with fetch API.
My fetch that calls an endpoint
fetch('http://localhost/registration-processing',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
firstName:firstName,
lastName:lastName,
username:username,
email:email,
password:password
})
})
.then((response)=>{
if(response.ok){
return response.json();
}
})
.then((data)=>{
console.log('Response:'+data);
})
.catch((err)=>{
console.error('Error is this:'+err);
})
I didn’t explicitly write the port in ‘localhost’ since Apache runs on port 80.Fetch worked absolutely fine before installing React, where I used plain JS. Now I get message: Access to fetch at 'http://localhost/registration-processing' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But I tried with using mode:'no-cors'
in fetch, and I get successful response(.then is executed, not catch) but result is Response:undefined
,even after I tried with echo json_encode(object)
to return value , because I think that app.php is unreachable, which is made for handling all routes and fetch requests.
I tried with configuring .htaccess like this, but no results
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /back-end/app.php [QSA,L]
This is my project structure:
├── back-end/
│ ├── app.php
│ └── .htaccess
├── front-end/
│ ├── react-environment(where fetch is)
So, I don’t know what could be a problem and how to fix this. Also one note: There are not problems when I use php -S localhost:8000
, but errors keep showing when I use Apache server via Laragon.