简体   繁体   中英

Translating Python API call to NodeJS Axios api call - how do I format it correctly?

I'm getting a 400 error and isAxiosError: true . I think the problem is the auth line is not formatted correctly, or I'm not quite understanding how params work in axios and what's needed by the api? What am I doing wrong in my translating of python to Axios/JS? Here's the Voila Norbert API documentation .

Here's my Axios api call.

axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
  params: {
    auth: {any_string: API_KEY},
    data: { 
      domain: 'amazon.com',
      name: 'Jeff Bezos'
    }
  }
})

Here's the python version:

API_TOKEN = 'abcde'

req = requests.post(
  'https://api.voilanorbert.com/2018-01-08/search/name',
  auth=('any_string', API_TOKEN),
  data = {
      'name': 'Cyril Nicodeme',
      'domain': 'reflectiv.net'
  }
)

According to their documentation, https://github.com/axios/axios , you need to give auth as a separate field, not inside params :

axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
  auth: {
    username: 'any_string',
    password: API_KEY
  },
  data: { 
    domain: 'amazon.com',
    name: 'Jeff Bezos'
  }
})

Updated: removed the nesting of data in params . They should be sent as POST body, not URL params.

I am a year late with this answer but I found your question while dealing with this same error with the same API. The API documentation's suggested Python code works for me with a successful response, but I want to do it in Node and the JS code returns a 400 error. I'm sharing my solution in case it helps others in the future.

I believe the core issue is that the API expects the data to be posted as form data, not as JSON. I followed an example in another post to post form data with Axios but still was receiving a 400 error.

Then I tried posting it using the request package instead of Axios, and that results in a successful response (no error):

const request = require('request');

var data = {'name': 'Jeff Bezos', 'domain': 'amazon.com'};

request.post({
    url: 'https://any_string:API_KEY@api.voilanorbert.com/2018-01-08/search/name',
    form: data,
}, function(error, response, body){
    console.log(body);
});

This example works when the data is included in the form: field but does not work when it is in body:

Please note the request package is deprecated and in maintenance mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM