POST 使用 Fetch 请求 API?

POST Request with 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 请求?

长话短说,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
});

查看 fetch 文档以获得更多好处和陷阱:

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

请注意,由于您正在执行异步 try/catch 模式,因此您只需在我的示例中省略 then() 函数 ;)

如果您想发出一个简单的 post 请求而不发送数据 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
});

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

POST 将数据形成为 PHP-script 的最佳方法是 Fetch API。这是一个例子:

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(console.error)
}
<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);

这是使用节点获取的 POST 请求的解决方案,其中 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

在这个article中,我描述了fetch()的第二个参数。

提交JSON数据

const user =  { name:  'Sabesan', surname:  'Sathananthan'  };
const response = await fetch('/article/fetch/post/user', {
  method: 'POST',
  headers: {
   'Content-Type': 'application/json;charset=utf-8'
  }, 
  body: JSON.stringify(user) 
});

用于提交表单

const form = document.querySelector('form');

const response = await fetch('/users', {
  method: 'POST',
  body: new FormData(form)
})

用于文件上传

const input = document.querySelector('input[type="file"]');

const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');

fetch('/avatars', {
  method: 'POST',
  body: data
});

2021 答案:以防万一您在这里寻找如何使用 async/await 或 promises 进行 GET 和 POST 获取 api 请求,与 axios 相比。

我正在使用 jsonplaceholder fake API 来演示:

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

         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()

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

    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()

使用 Promises 的 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)
  })

POST 使用 Promises 的请求:

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()

POST 使用 Axios 请求:

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()