如何使用 axios get 请求发送正文数据和标头?

IT技术 reactjs http get axios
2021-05-22 21:23:46

我试过了

axios.get(url, {headers:{},data:{}}) 

但它不适用于此。

4个回答

你应该参考https://github.com/axios/axios#request-config

检查数据和标题部分。

你可以试试这个:

const getData = async () => {
    try {
        const response = await axios.get(`https://jsonplaceholder.typicode.com/posts`, {
            method: 'GET',
            body: JSON.stringify({
                id: id,
                title: 'title is here',
                body: 'body is here',
                userId: 1
            }),
            headers: {
                "Content-type": "application/json; charset=UTF-8"
            }
        })
            .then(response => response.json())
            .then(json => console.log(json));
        console.warn(response.data);
    } catch (error) {
        console.warn(error);
    }
}

据我所知,您无法使用 GET 请求发送正文数据。使用 get 您只能拥有标题。只需简单地更改为 POST,然后您就可以执行以下操作:

const bodyParameters = {
      key: "value",
    };
    const config = {
      headers: { Authorization: `Bearer ${userToken}` }, 
    };
      axios.post("http://localhost:5000/user", bodyParameters, config)
      .then((res)=> {
       console.log(res)
      })
      .catch((err) => console.log(err));
  };

或者如果您想使用 GET 请求发送标头

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

//data是作为请求正文发送的数据 // 仅适用于请求方法 'PUT'、'POST'、'DELETE 和 'PATCH'

https://stackoverflow.com/a/54008789