如何使用javascript中的'POST'方法从此api获取数据

时间:2021-01-28 16:55:19

标签: javascript fetch

url---http://eign-backend.herokuapp.com/property/get-property/17/

我必须写完整的 url 直到“/17/”还是什么!

const response=await fetch('url',{
      method:'POST',
      body: JSON.stringify(
        {
         //what should I write here
        }
      ),
      headers:{
        headers: {'Content-Type':'application/json'},
      }
    })
    const data=await response.json();
    console.log(data);
}

3 个答案:

答案 0 :(得分:0)

fetch 中的第一个参数是 实际 url

 const response=await fetch('http://eign-backend.herokuapp.com/property/get-property/17/',{
          method:'POST',
          body: JSON.stringify(
            {
             //what should I write here => write whatever you want to send in this post request's body
            }
          ),
          headers:{
            headers: {'Content-Type':'application/json'},
          }
        })
 const data=await response.json();
 console.log(data);
  

考虑先阅读一些documentation

答案 1 :(得分:-1)

您可以直接对该 URL 发出 POST 请求。可以发送没有正文的 POST 请求,而是使用查询字符串参数,但是如果不需要正文,它应该是 get 请求而不是 POST。但请注意,如果您的参数包含无效的 HTTP 字符,则必须对其进行编码。

var requestOptions = {
  method: 'POST',
  redirect: 'follow'
};

fetch("http://eign-backend.herokuapp.com/property/get-property/17/", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

这是我使用过的 fetch 调用。

答案 2 :(得分:-3)

试试这个


async function postData(url = '', data = {}) {
  
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });