I have been tasked to create a node CLI based software utilizing node.js. Below is a simple video example. I have managed to ajax to API to get the data, but i require this data to be converted into a CSV and saved locally to a specific file with timestamp.
I'm assuming the saving to file would have to be achieved in PHP by performing a Ajax post request with the relevant data. But whenever I attempt to post to a simple php test file I get a 400 bad request error.
Im not using a browser to perform the ajax requests (using console commands in conEmu64), which i think is the issue when attempting a HttpRequest. The ajax get request works fine at retrieving the data from api, just unsure why this error happens on the post requests to local PHP file.
- Can anyone suggest best approach at Ajax posting without a browser?
- Should I instead be attempting to save the CSV purely in java script?
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);
});
}