Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL command to Axios request with json data

I've got this cURL request working perfectly on remote interface just as it should

curl -XGET "https://server.host:8080/peregrine" -d '{"exchanges":["kucoin", "kraken"],"volume":10}' -k

I'm trying to build a little frontend app with Vue.js and need the above converted to an Axios get request. I've been trying the following so far:

axios({
      method: 'get',
      url: 'https://server.host/peregrine',
      data: {"exchanges":["kucoin", "kraken"],"volume":10}
    });

putting params instead of data makes it a URL and remote server says that it received no data.

What am I doing wrong? Thanks.

like image 576
Ruslan K Avatar asked Jul 03 '19 09:07

Ruslan K


People also ask

Does Axios work with JSON?

By default, Axios converts Javascript data to JSON (including AJAX). The “content-type” header is also set to “application/json.” If you send a serialized JSON object as data, however, Axios considers it as “application/x-www-form-urlencoded” (form-encoded request body).

How do I use the curl command to request?

To make a GET request using Curl, run the curl command followed by the target URL. Curl automatically selects the HTTP GET request method unless you use the -X, --request, or -d command-line option. The target URL is passed as the first command-line option.

How do I POST request body with curl?

To post data in the body of a request message using Curl, you need to pass the data to Curl using the -d or --data command line switch. The Content-Type header indicates the data type in the body of the request message.


2 Answers

Likely the problem could be that using GET you cannot pass data like you are doing. You have to pass them as query parameter. Try to change your call with:

axios.get('https://server.host/peregrine', {
    params: {"exchanges":["kucoin", "kraken"],"volume":10}
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  
like image 127
Wolfetto Avatar answered Sep 20 '22 03:09

Wolfetto


GET requests should not have request bodies.

CURL will allow you to make a GET request with one, but XMLHttpRequest and fetch (the HTTP APIs in browsers which axios wraps) will not.

Make a POST request instead. You might need to change the server-side code to support this.

like image 39
Quentin Avatar answered Sep 22 '22 03:09

Quentin