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

时间:2020-05-01 21:33:01

标签: reactjs http get axios

我尝试过

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

但是这不起作用。

4 个答案:

答案 0 :(得分:1)

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

检查该部分的数据和标题。

答案 1 :(得分:0)

您可以尝试以下方法:

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

答案 2 :(得分:0)

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

https://stackoverflow.com/a/54008789

答案 3 :(得分:-2)

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

$tables = array('table1', 'table2', 'table3');
$array_of_tables = array('SELECT column1, column2 FROM ', $tables[0]);

for($i = 1; $i < count($tables); $i++){
    array_push($array_of_tables, "UNION SELECT column1, column2 FROM " . $tables[$i]);
}

array_push($array_of_tables, "ORDER BY 'eng'" . '"');

$sql = implode('', $array_of_tables);

或者如果您要发送带有GET请求的标头

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