1

I have api running at http://localhost:81/log_api.php, then I have React app on the same computer running at http://localhost:3000. Below is the codes for React app :

import React, { Component } from 'react';
import axios from 'axios';

class Logging extends Component {

   state={
       pl_log:[]
     }

     async componentDidMount(){
        await axios.get("http://localhost:81/log_api.php")
         .then(response=>this.setState(
             {
               pl_log: response.data

             } ))

        console.log(this.state)       
     }


   render(){
       return(
           <div>
               Logging
           </div>
       )
   }
  }

  export default Logging;

Console.log shows some errors : enter image description here

I have also directly visited http://localhost:81/log_api.php , no problem at all. It shows the JSON data on the browser. The problem only occurs when I use axios in React.

filename : log_api.php

<?php



$link = mysqli_connect("127.0.0.1:3307", "root", "root", "masterdb");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$sql = $link -> query("SELECT * FROM pl_log");
$result=array();

while ($data = $sql -> fetch_assoc()){
    $result[]=$data;
}
echo json_encode($result);


mysql_close($link);

?>

Network screenshot : enter image description here

brandoncraig
  • 53
  • 3
  • 10
Nano Man
  • 73
  • 2
  • 5
  • Is your PHP server CORS ready? –  Apr 16 '20 at 08:52
  • I have added CORS extension on Chrome. – Nano Man Apr 16 '20 at 08:54
  • I run MAMP server on my local computer. – Nano Man Apr 16 '20 at 08:55
  • 500 Error number means the server has a general problem. 503 indicates a runtime error. – Reporter Apr 16 '20 at 08:57
  • can you check the network tab and take a screenshot of the error – Quantumass Apr 16 '20 at 11:10
  • It's not a CORS issue, that would fail with a different error. A 500 error indicates something went wrong in your PHP script. In the network inspector of your browser, you should still be able to access the response your API sent. Assuming you have [error reporting enabled](https://stackoverflow.com/a/21429652/1941241), that may tell you what's going wrong. – rickdenhaan Apr 16 '20 at 11:10
  • 1
    You are mixing mysql apis. `mysql_close()` cannot be used with a `mysqli` connection. I'd venture a guess that it fails in the browser as well, but you don't see it since it's the very last thing PHP tries to do. If you look at the network tab when you directly request it, does it also show a 500 error (despite showing the correct JSON)? – rickdenhaan Apr 16 '20 at 19:58

1 Answers1

0

You may try with Ip address http://127.0.0.1

Hope it will work for you

tapu74
  • 1,081
  • 10
  • 14