POST Request with Fetch API?

后端 未结 5 1726
鱼传尺愫
鱼传尺愫 2020-12-01 03:10

I know that with the new Fetch API (used here with ES2017\'s async/await) you can make a GET request like this:

async getData() {
          


        
相关标签:
5条回答
  • 2020-12-01 03:15

    Here is a complete example: After spending hours tinkering with incomplete code snippets I finally managed to post some json from javascript, pick it up using php on a server, added a data field and finally updated the original web page. Here is the HTML, the PHP and the JS. My thanks to everyone who posted the original code fragments collected here. Similar code is on-line here: https://www.nbest.co.uk/Fetch/index.php

    <!DOCTYPE HTML>
    <!-- Save this to index.php and view this page in your browser -->
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Javascript Fetch Example</title>
    </head>
    
    <body>
    <h1>Javascript Fetch Example</h1>
    <p>Save this to index.php and view this page in your browser.</p>
    
    <button type="button" onclick="myButtonClick()">Press Me</button>
    
    <p id="before">This is the JSON before the fetch.</p>
    <p id="after">This is the JSON after the fetch.</p>
    
    <script src="fetch.js"></script>
    
    </body>
    </html>
    <!-- --------------------------------------------------------- -->
    
    // Save this as fetch.js --------------------------------------------------------------------------
    
    function success(json) {
      document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json);
      console.log("AFTER: " + JSON.stringify(json));
    } // ----------------------------------------------------------------------------------------------
    
    function failure(error) {
      document.getElementById('after').innerHTML = "ERROR: " + error;
      console.log("ERROR: " + error);
    } // ----------------------------------------------------------------------------------------------
    
    function myButtonClick() {
      var url    = 'json.php';
      var before = {foo: 'Hello World!'};
    
      document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before);
      console.log("BEFORE: " + JSON.stringify(before));
    
      fetch(url, {
        method: 'POST', 
        body: JSON.stringify(before),
        headers:{
          'Content-Type': 'application/json'
        }
      }).then(res => res.json())
      .then(response => success(response))
      .catch(error => failure(error));
    } // ----------------------------------------------------------------------------------------------
    
    <?php
      // Save this to json.php ---------------------------------------
      $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
    
      if ($contentType === "application/json") {
        $content = trim(file_get_contents("php://input"));
    
        $decoded = json_decode($content, true);
    
        $decoded['bar'] = "Hello World AGAIN!";    // Add some data to be returned.
    
        $reply = json_encode($decoded);
      }  
    
      header("Content-Type: application/json; charset=UTF-8");
      echo $reply;
      // -------------------------------------------------------------
    ?>
    
    0 讨论(0)
  • 2020-12-01 03:18

    Long story short, Fetch also allows you to pass an object for a more personalized request:

    fetch("http://example.com/api/endpoint/", {
      method: "post",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    
      //make sure to serialize your JSON body
      body: JSON.stringify({
        name: myName,
        password: myPassword
      })
    })
    .then( (response) => { 
       //do something awesome that makes the world a better place
    });
    

    Check out the fetch documentation for even more goodies and gotchas:

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Please note that since you're doing an async try/catch pattern, you'll just omit the then() function in my example ;)

    0 讨论(0)
  • 2020-12-01 03:29

    The best way to POST form data to a PHP-script is the Fetch API. Here is an example:

    function postData() {
        const form = document.getElementById('form');
        let data = new FormData();
        data.append('name', form.name.value);
    
        fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {
            if (!response.ok){
                throw new Error('Network response was not ok.');
            }
        }).catch((err) => {
        	console.log(err);
        });
    }
    <form id="form" action="javascript:postData()">
        <input id="name" name="name" placeholder="Name" type="text" required>
        <input type="submit" value="Submit">
    </form>

    Here is a very basic example of a PHP-script that takes the data and sends an email:

    <?php
        header('Content-type: text/html; charset=utf-8');
    
        if (isset($_POST['name'])) {
            $name = $_POST['name'];
        }
    
        $to = "test@example.com";
        $subject = "New name submitted";
        $body = "You received the following name: $name";
    
        mail($to, $subject, $body);
    
    0 讨论(0)
  • 2020-12-01 03:34

    if you want to make a simple post request without sending data as JSON.

    fetch("/url-to-post",
    {
        method: "POST",
    
        // whatever data you want to post with a key-value pair
    
        body: "name=manas&age=20",
        headers: 
        {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    
    }).then((response) => 
    { 
        // do something awesome that makes the world a better place
    });
    
    0 讨论(0)
  • 2020-12-01 03:37

    Here is a solution for a POST request using node-fetch, with async/await.

    async function post(data) {
        try {
            // Create request to api service
            const req = await fetch('http://127.0.0.1/api', {
                method: 'POST',
                headers: { 'Content-Type':'application/json' },
                
                // format the data
                body: JSON.stringify({
                    id: data.id,
                    foo: data.foo,
                    bar: data.bar
                }),
            });
            
            const res = await req.json();
    
            // Log success message
            console.log(res);                
        } catch(err) {
            console.error(`ERROR: ${err}`);
        }
    }
    
    // Call your function
    post() // with your parameter of Course
    
    0 讨论(0)
提交回复
热议问题