2

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

Claire
  • 101
  • 8
  • You need to add a setting to your htaccess file on your API directory root. See [this solution](https://stackoverflow.com/questions/13421463/htaccess-access-control-allow-origin) – Jamie_D Oct 22 '20 at 11:52

1 Answers1

1

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.

Nick Dawes
  • 2,089
  • 1
  • 13
  • 20
  • Thank you Nick, couse it's my first day to learn ReactJS, and just test how to use axios to get/post data. so I did not use any framework in frontedend and used PHP REST API in the back and. and I added my code above. – Claire Oct 22 '20 at 12:19
  • What are you using for the backend? Can you share some code from your REST API? – Nick Dawes Oct 22 '20 at 12:36
  • Hi Nick, I have edited my question, and the PHP code is my backend code the file name is api.php(all api from this file, for example if I use pure javascript fetch data, I will write like this: var url = './api/api.php?action=read';). The file includes my db.php(db connect and query) and session.php. To test reactJS I add a new file named read.php and the code showed above. – Claire Oct 22 '20 at 12:47
  • 1
    Try add ```header("Access-Control-Allow-Origin: 'http://localhost:3000'");``` to your api.php, just beneath your other header declaration. – Nick Dawes Oct 22 '20 at 12:55
  • Thank you Nick, I followed your answer and solved the problem. Just add this line in the beginning of the api file and it worked: header("Access-Control-Allow-Origin: *"); Thank you again. – Claire Oct 22 '20 at 12:57