Home > Software engineering >  What is the best way to see errors from PHP scripts when you are using React as the Frontend?
What is the best way to see errors from PHP scripts when you are using React as the Frontend?

Time:11-18

I am using React as the frontend and setting up a PHP backend with it.

I successfully connected the two by putting this React project inside of my htdocs folder inside of XAMPP.

When I make the request to the below URL

    useEffect(() => {
        fetch("http://localhost:80/php_w_r/api/index.php?url=Users/index", {
            method: 'GET',
        }).then((res) => res.json())
        .then((data) => {
            console.log(data)
        }).catch(err => console.log(err))
        })

The good thing is that it works I get an object back. Here is my PHP code.

<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

class Users extends Controller
{
    public function __construct()
    {
        $this->userModel = $this->model('User');
    }
    public function index() {
        $s = $this->userModel->login();
       $json_data =  json_encode((array) $s);
       print_r($json_data);
    }
}

The real pain I'm having is debugging when things go bad on the PHP side of things. The way I was able to solve this was by opening the developer console.

I kept getting the error message:

Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

Is there any way I can make development easier without having to open up the console every time I think there is something wrong with the PHP code ? Even when there is something wrong, I don't receive a very helpful message as to why things might be wrong on the PHP side of things. The only message I receive is

Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

Before I was able to see any errors coming from PHP in my views directory. Because I am now using React those errors no longer appear.

I am taking setting up my backend from this tutorial on Udemy.

https://www.udemy.com/course/object-oriented-php-mvc/

CodePudding user response:

You can

  1. Log any debug information (such as print_r output) from PHP to a file instead of outputting it. Also ensure that PHP's on-screen error reporting is switched off, and error logging to a file is switched on.

And/or

  1. use the Network tool in your browser's developer tools to examine the raw response coming back from the server for each request, so you don't have to worry about the JSON parse errors.

P.S. Don't use tools like print_r for normal output - it's intended as a debugging tool and may add extra content you weren't expecting. Just use echo or print for regular output.

  • Related