Подтвердить что ты не робот

Запрос POST с API-интерфейсом Fetch?

Я знаю, что с новым API-интерфейсом Fetch (используется здесь с 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?

4b9b3361

Ответ 1

Короче говоря, 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
});

Посмотрите документацию на выборку для еще большего количества полезных свойств и gotchas:

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

Обратите внимание, что, поскольку вы используете шаблон async try/catch, вы просто опустите функцию then() в моем примере;)

Ответ 2

если вы хотите сделать простой почтовый запрос без отправки данных в формате 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
});

Ответ 3

Вот полный пример: после нескольких часов работы с неполными фрагментами кода мне наконец-то удалось опубликовать json из javascript, взять его с помощью 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;
  // -------------------------------------------------------------
?>

Ответ 4

Используйте fetch() для POST JSON-кодированных данных.

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be 'string' or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

Фрагмент JavaScript

function createGist(opts) {
  ChromeSamples.log('Posting request to GitHub API...');
  fetch('https://api.github.com/gists', {
    method: 'post',
    body: JSON.stringify(opts)
  }).then(function(response) {
    return response.json();
  }).then(function(data) {
    ChromeSamples.log('Created Gist:', data.html_url);
  });
}

function submitGist() {
  var content = document.querySelector('textarea').value;
  if (content) {
    createGist({
      description: 'Fetch API Post example',
      public: true,
      files: {
        'test.js': {
          content: content
        }
      }
    });
  } else {
    ChromeSamples.log('Please enter in content to POST to a new Gist.');
  }
}

var submitBtn = document.querySelector('button');
submitBtn.addEventListener('click', submitGist);