Search code examples
node.jsposthttp-postaxiosnode-request

Post request to php Api from nodejs with data


I have some api running at example.com/api.php

In order to use the api with ajax I use this code:

        $.ajax({
            url: 'https://example.com/api.php',
            method: 'post',
            data: {'pass': 'mypass', 'action': 'someaction'},
        }).done(function(results){
            //results = JSON.parse(results); //no need to parse it!
            console.log(results);

            });
        })

I tried to achieve the same thing with node.js But I can't figure out how to send the data.

I tried many approaches and here's one of them:

axios.post('https://example.com/api.php', {
    'pass': 'passs',
    'action': 'myaction'
})
.then((res) => {
  console.log(`statusCode: ${res.statusCode}`)
  console.log(res)
  console.log(`statusCode: ${res.data}`)
})
.catch((error) => {
  console.error(error)
})

But I can't get it to work at all! res.statusCode returns undefined and res.data returns nothing at all. The server logs the actions each user tries to execute via the api. the php api has something like the this :

    if($_POST['pass']== thePassword && $_POST['action']=='aSpecifiAction'){
// log the action,
//execute the action
}

my action do not appear in the log, which means that my axios code is NOT sending any data to the api. So how to I get it to behave like the jquery code above?

Using axios is not a must, if there's a simpler solution with request or any other module it's fine.

Thanks in advance


Solution

  • Someone helped me on github to find the issue. The issue is "that jQuery defaults to using the application/x-www-form-urlencoded format for POST data, whereas axios defaults to JSON"

    In this link they expalin in details https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

    The solution :

    const axios = require('axios')
    
    const qs = require('qs');
    axios.post('https://example.com/api.php',  qs.stringify({
        'pass': 'passs',
        'action': 'myaction'
    }))
    .then((res) => {
      console.log(`statusCode: ${res.statusCode}`)
      console.log(res)
      console.log(`statusCode: ${res.data}`)
    })
    .catch((error) => {
      console.error(error)
    })