I'm doing a ReactJS frontend App and get data from an API created with PHP Rest API, but my react is host on localhost:3000, but my php file is hosted on localhost:80. so not sure how to write the baseurl in react, cause it always got some error until now. May I know how to solve it? Thank you.
error:
Access to XMLHttpRequest at 'http://localhost/reacttest/src/api/read.php' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:184 GET http://localhost/reacttest/src/api/read.php net::ERR_FAILED
ReactJS:
import React from 'react';
// import logo from './logo.svg';
import './App.css';
import axios from "axios";
const baseUrl = "http://localhost:80/reacttest/src/api";
const sampleGet = async () => {
const result = await axios.get(baseUrl + "/read.php");
console.log(result);
};
const samplePost = async () => {
const result = await axios.post(baseUrl + "/posts", {
sampleData: "nabezap"
});
console.log(result);
};
const sampleDelete = async () => {
const result = await axios.delete(baseUrl + "/posts/4");
console.log(result);
};
function App() {
return (
<div className="App">
<button onClick={sampleGet}>GET</button>
<button onClick={samplePost}>POST</button>
<button onClick={sampleDelete}>DELETE</button>
</div>
);
}
export default App;
read.php:
<?php
header('Content-Type: application/json;charset=utf-8');// all echo statements are json_encode
include('se.php');
include('db.php');
session_start();
$doctordb = new doctorModel; //instantiate database to start using
$result = $doctordb->showDoctorinfo();
if($result == false) {
http_response_code(204); // no content
} elseif(is_array($result)) {
http_response_code(200); //success
echo json_encode($result);
}
?>