React axios with PHP Rest API , how to write the baseurl

Viewed 800

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);
} 
?>

api.php: enter image description here

1 Answers

The base url is correct (80 is default) and if you check your network tab in dev tools, you’ll see the request did in fact go out and received the expected response.

The issue is with your REST API. The clue is in the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

This means the server received the request, processed it and returned a response— but it didn’t attach a Access-Control-Allow-Origin: ‘http://localhost:3000’ header. When your browser receives the response from the API, it checks for this header and refuses javascript access to the response data if it’s missing. This is normal.

Setting up CORS on your REST API is the way to go. What framework (if any) are you using? I’ll edit this answer with more info once I know.

Related