使用Fetch API发布POST请求?

时间:2016-09-19 05:03:56

标签: javascript fetch-api

我知道使用新的Fetch API(此处使用ES2017的async / await),您可以像这样发出GET请求:

async getData() {
    try {
        let response = await fetch('https://example.com/api');
        let responseJson = await response.json();
        console.log(responseJson);
    } catch(error) {
        console.error(error);
    }
}

但是你如何发出POST请求?

6 个答案:

答案 0 :(得分:47)

长话短说,Fetch还允许您传递一个对象以获得更个性化的请求:

1. User has_many requests (with column requests.user_id) 
2. Request has_one user(with column requests.agent_id)

查看获取文档,了解更多好东西和陷阱:

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

请注意,由于您正在执行异步尝试/捕获模式,因此您只需省略我示例中的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 }); 函数;)

答案 1 :(得分:6)

如果你想发一个简单的帖子请求而不用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
});

答案 2 :(得分:1)

将表单数据发布到PHP脚本的最佳方法是Fetch API。这是一个示例:

function postData() {
    const form = document.getElementById('form');
    const 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>

这是一个PHP脚本的非常基本的示例,该脚本获取数据并发送电子邮件:

<?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);

答案 3 :(得分:1)

这是使用带有异步/等待功能的节点获取的POST请求的解决方案。

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 ofCourse

答案 4 :(得分:0)

这是一个完整的示例:花了几个小时修改不完整的代码片段后,我终于设法从javascript中发布了一些json,在服务器上使用php将其提取,添加了数据字段,并最终更新了原始网页。这是HTML,PHP和JS。感谢所有在此处发布原始代码片段的人。此处类似的代码在线: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;
  // -------------------------------------------------------------
?>

答案 5 :(得分:0)

2021 答案:以防万一您登陆这里寻找与 axios 相比如何使用 async/await 或 promise 发出 GET 和 POST Fetch api 请求。

我使用 jsonplaceholder fake API 来演示:

使用 async/await 获取 api GET 请求:

         const asyncGetCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                 const data = await response.json();
                // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
            // enter your logic for when there is an error (ex. error toast)
                  console.log(error)
                 } 
            }


          asyncGetCall()

使用 async/await 获取 api POST 请求:

    const asyncPostCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
                 method: 'POST',
                 headers: {
                   'Content-Type': 'application/json'
                   },
                   body: JSON.stringify({
             // your expected POST request payload goes here
                     title: "My post title",
                     body: "My post content."
                    })
                 });
                 const data = await response.json();
              // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
             // enter your logic for when there is an error (ex. error toast)

                  console.log(error)
                 } 
            }

asyncPostCall()

使用 Promise 的 GET 请求:

  fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
    // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })

使用 Promise 的 POST 请求:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
   body: JSON.stringify({
     // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
})
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
  // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })  

使用 Axios 的 GET 请求:

        const axiosGetCall = async () => {
            try {
              const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
    // enter you logic when the fetch is successful
              console.log(`data: `, data)
           
            } catch (error) {
    // enter your logic for when there is an error (ex. error toast)
              console.log(`error: `, error)
            }
          }
    
    axiosGetCall()

使用 Axios 的 POST 请求:

const axiosPostCall = async () => {
    try {
      const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts',  {
      // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
   // enter you logic when the fetch is successful
      console.log(`data: `, data)
   
    } catch (error) {
  // enter your logic for when there is an error (ex. error toast)
      console.log(`error: `, error)
    }
  }


axiosPostCall()