简体   繁体   中英

Integrate Postman code into webpage. Javascript fetch client side, php server side

I've built a backend that inserts and reads contents from a database with PHP and MySQLi. I've setup the PHP as REST API endpoints and can GET and POST correctly using Postman.I'm trying to create a client side endpoint to send the API requests but can't figure out how to correctly integrate the code from Postman into the client side.

This is the server side endpoint to GET from the database:

    <?php
    include_once('config.php');
    $task = isset($_GET['task']) ? mysqli_real_escape_string($conn, $_GET['task']) :  "";
    $sql = "SELECT * FROM `my_to_do_db`.`my_to_do_tb` WHERE task='{$task}';";
    
    $get_data_query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
        if(mysqli_num_rows($get_data_query)!=0){
        $result = array();
        
        while($r = mysqli_fetch_array($get_data_query)){
            extract($r);
            $result[] = array("Task" => $task, "Date" => $date, 'Priority' => $priority);
        }
        $json = array("status" => 1, "info" => $result);
    }
    else{
        $json = array("status" => 0, "error" => "To-Do not found!");
    }
    @mysqli_close($conn);
    // Set Content-type to JSON
    header('Content-type: application/json');
    echo json_encode($json);

It works correctly when I GET with Postman. Here is the code Postman exports when I click "code" (Javascript fetch):

    var urlencoded = new URLSearchParams();

    var requestOptions = {
        method: 'GET',
        body: urlencoded,
        redirect: 'follow'
    };

    fetch("http://localhost/endPointTest/info.php?task=Build API CRUD app", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

Here's how I've been trying to integrate it into a client side page:

    <!DOCTYPE html>
    <html>
     <head>
      <title>Get Info API client side</title>
     </head>
     <body>
        <h3 class="displayData"></h3>
        <button type="submit" id="getData">Submit</button>
    
     <script type="text/javascript">
        const displayData = document.querySelector('.displayData')

        document.getElementById('getData').addEventListener
        ('click', getData);

        var urlencoded = new URLSearchParams();

        var requestOptions = {
          method: 'GET',
          body: urlencoded,
          redirect: 'follow'
        };

        function getData(){
            fetch("http://localhost/endPointTest/info.php?task=Do some stuff", requestOptions)
            .then(response => {
                return response.json()
            })
            .then(data => {
                console.log(data)
                displayData.innerHTML = data
            })
        }
    </script> 
    </body>
    </html>

My question is basically: how can I integrate the code from Postman into real world pages?

It turns out the problem was that Postman is for testing and doesn't work like a browser. CORS isn't an issue with Postman but it is for a browser, after I added the needed header to the PHP page the API was able to connect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM