The console.log()
statement returns a blank array because it is being executed before the response from your POST request is returned. This is due to the fact that axios
executes requests asynchronously.
To access the data returned from the network request without writing other functions, you need to have your code in the then
block like so:
const axios = require('axios');
let api = []
axios.post('http://127.0.0.1:8000/make_json/', {
api:"{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/1190896199.pdf', 'Title': 'Corrigendum'},{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/3916152215.pdf', 'Title': 'Notification '},{'Link': 'http://www.nia.nic.in/', 'Title': ' Official Website'}"
})
.then(response => {
api = response.data
console.log(api)
// other code using `api`...
})
Another option, if you're using at least version 7.6 of Node, is to wrap your code in an async
function and await
the result:
const axios = require('axios');
async function myCode() {
const response = await axios.post('http://127.0.0.1:8000/make_json/', {
api:"{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/1190896199.pdf', 'Title': 'Corrigendum'},{'Link': 'media/pdf/details/all-india-govt-jobs/other-all-india-govt-jobs/3916152215.pdf', 'Title': 'Notification '},{'Link': 'http://www.nia.nic.in/', 'Title': ' Official Website'}"
})
let api = response.data
console.log(api)
// other code using `api`...
}
myCode() // note that `myCode` will run asynchronously