如何使用axios调用GET API在BODY中发送数据?

时间:2019-01-02 15:03:35

标签: reactjs api get axios

我正在尝试使用GET方法在正文中发送数据。 当我尝试使用POSTMAN / cURL / Python运行时,它运行良好,但使用AXIOS(ReactJS)时,则无法运行。

cURL:

curl -X GET \
  http://127.0.0.1:8000/xyz/xyz/ayx-api/ \
  -H 'Authorization: Token 980e4e673a9cfb4c99cb35313f65a446aa44faf7' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 1ee27393-b4b0-446a-b613-bd319e02e3c8' \
  -H 'cache-control: no-cache' \
  -d '{"dataId": 1, "date": "2018-03-01", "days": 9 }'

此卷曲效果很好

使用Axios:

import axios from 'axios';

const baseUrl = process.env.BACKEND_SERVER_URL;

export const fetchDataObjects = async() => {
    const header = {
            'Content-Type': 'application/json',
            'Authorization': `Token ${localStorage.token}`,

        }
    const data ={"dataId": 1, "date": "2018-03-01", "days": 9 }
    const res= await axios.get(`${baseUrl}/ayx-api/`,{data:JSON.stringify(data)}, {headers: header})
    // above line need to helop
    return res.data;
  }

如何在get方法中使用axios在体内发送数据?

谢谢。

1 个答案:

答案 0 :(得分:2)

The HTTP GET method requests shouldn't have a request body,axios无法使用正文创建GET请求。它也无法为您创建查询字符串,如果您想传递查询字符串,则必须手动执行,或使用类似qs的操作:

axios.get(`${baseUrl}/ayx-api/${qs.stringify(data)}`)
相关问题