Heim  >  Fragen und Antworten  >  Hauptteil

Holen: JSON-Daten übertragen

<p>Ich versuche, ein JSON-Objekt mit der Methode fetch zu POSTEN. </p> <p>Nach meinem Verständnis muss ich ein stringifiziertes Objekt an den Hauptteil der Anfrage anhängen, zum Beispiel: </p> <pre class="brush:js;toolbar:false;">fetch("/echo/json/", { Überschriften: { 'Akzeptieren': 'application/json', 'Content-Type': 'application/json' }, Methode: „POST“, body: JSON.stringify({a: 1, b: 2}) }) .then(function(res){ console.log(res) }) .catch(function(res){ console.log(res) }) </pre> <p>Wenn ich das JSON-Echo von jsfiddle verwende, erwarte ich, dass ich das von mir gesendete Objekt sehen kann (<code>{a: 1, b: 2}</code>), aber das passiert nicht - Chrome Development Das Autorentool zeigt den JSON nicht einmal als Teil der Anfrage an, was bedeutet, dass er nicht gesendet wird. </p>
P粉348915572P粉348915572399 Tage vor483

Antworte allen(2)Ich werde antworten

  • P粉458725040

    P粉4587250402023-08-21 10:51:25

    我认为你的问题是jsfiddle只能处理form-urlencoded请求。但是正确的方法是将正确的json作为请求体传递:

    fetch('https://httpbin.org/post', {
      method: 'POST',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({a: 7, str: 'Some string: &=&'})
    }).then(res => res.json())
      .then(res => console.log(res));

    Antwort
    0
  • P粉819937486

    P粉8199374862023-08-21 10:15:17

    使用ES2017的async/await支持,这是如何进行POST JSON数据的方法:

    (async () => {
      const rawResponse = await fetch('https://httpbin.org/post', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({a: 1, b: 'Textual content'})
      });
      const content = await rawResponse.json();
    
      console.log(content);
    })();

    Antwort
    0
  • StornierenAntwort