I have been given the task of developing a node.js CLI software. I have successfully utilized ajax to fetch data from an API, but now I need to convert this data into a CSV file and save it locally with a timestamp.
My current approach involves using PHP to handle the saving process by making an Ajax post request with the necessary data. However, every time I try to post to a basic PHP test file, I encounter a 400 bad request error.
I am not executing the ajax requests in a browser (using console commands in conEmu64), which might be causing issues when attempting HttpRequests. The ajax get request works perfectly for fetching data from the api, so I'm unsure why I keep getting errors on the post requests to the local PHP file.
- Anyone have suggestions for the best way to perform Ajax posting without a browser?
- Should I consider saving the CSV file purely using JavaScript instead?
Attempt 1: Basic Javascript & XMLHttpRequest Module
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
function createCSV(request) {
var xhr = new XMLHttpRequest;
xhr.open('POST', 'server/save');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr);
if (xhr.status === 200) {
console.log('Name is now ' + xhr.responseText);
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(JSON.stringify({
name: 'John Smith',
age: 34
}));
}
Attempt 2: Axios Module
const axios = require('axios');
function createCSV(request) {
axios.post('server/save', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Check out this simple video demo