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

查看获取文档以获得更多的好东西和陷阱:

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

如何将表单数据POST到PHP脚本

最好的方法是利用Fetch API和FormData接口。下面是一个例子:

function postData() {
  const form = document.getElementById('form');
  const data = new FormData();
  data.append('name', form.name.value);
  try {
    const res = fetch('../php/contact.php', {
      method: 'POST',
      headers: {
        "content-type": "multipart/form-data"
      },
      body: data,
    });
    if (!res.ok) console.log(`POST failed with ${res.status}.`);
  } catch(err) {
    console.error(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);

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

我使用jsonplaceholder伪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()

GET请求使用Promises:

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

GET request using Axios:

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

这是一个使用node-fetch的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

这是一个完整的例子:在花了几个小时修补不完整的代码片段之后,我终于设法从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;
  // -------------------------------------------------------------
?>

在本文中,我描述了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) 
});

For submit form

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

相关内容

  • 没有找到相关文章

最新更新