【问题标题】:How to send body data and headers with axios get request?如何使用 axios get 请求发送正文数据和标头?
【发布时间】:2020-08-16 10:53:27
【问题描述】:

我试过了

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

但它不适用于这个。

【问题讨论】:

    标签: reactjs http get axios


    【解决方案1】:

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

    检查数据和标题部分。

    【讨论】:

    • 很遗憾,GET 方法中的数据不被视为正文。显然 Axios 不支持 GET 方法的请求正文。奇怪的是,像 Postman 这样的工具很容易支持它。我也在寻找解决方案。
    【解决方案2】:

    你可以试试这个:

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

    【讨论】:

      【解决方案3】:

      据我所知,您无法使用 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
        });  
      

      【讨论】:

      • 2014 年以后的标准允许获取正文
      【解决方案4】:

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

      https://stackoverflow.com/a/54008789

      【讨论】:

        猜你喜欢
        • 2019-10-21
        • 1970-01-01
        • 2021-08-13
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多