"Invalid Ajax post request through the CLI, resulting in 400 error

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

Answer №1

To achieve this, you can utilize Node.js and consider implementing FS in your project.

The original answer can be found at Write to a CSV in Node.js

You can use the fs module (https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):

var infoReturnedFromAxiosGet;
var timeStamp;
var fs = require('fs');

fs.writeFile('yourfoldername/' + timeStamp + '.csv', infoReturnedFromAxiosGet, 'utf8', function (err) {
  if (err) {
    console.log('An error occurred - file may not have been saved or a corrupted file was saved.');
  } else{
    console.log('File has been successfully saved!');
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve data from an external HTML file using JavaScript

Can someone assist me? I am working on a webpage that generates a table displaying high tide values in Venice from this link: http://93.62.201.235/maree/ESPORTAZIONI/MESE/Stazione_PuntaSalute_CanalGrande.html. I am trying to extract a specific value (the t ...

Utilizing Node, Jade, Express, and Sqlite: Implementing a MiniMap on a Leaflet Map

I recently created a map using Node, Jade, Express, and Sqlite. I am now attempting to incorporate a minimap using a plugin, but the function I added does not seem to be working correctly. Below is the code snippet that I have been working with: In my HTM ...

Rocket Calculations Made Easy

Recently, I acquired a cutting-edge 3D system along with a set of coordinates: Initial coordinates (x, y, z) for a rocket (located on the ground) Target coordinates (x, y, z) for the rocket's destination (also on the ground) Here are some essential ...

Tips for organizing and refining ngTable data that is stored in milliseconds?

I'm new to Angularjs and I could use some assistance with sorting dates in milliseconds in descending order, as well as implementing a filter for the table columns. I've set up a plunker example, but when I enter a filter parameter, the data does ...

Transforming attributes into a JSON format

Click here to view my JSFiddle example function testing() { foo = canvas.getObjects(); bar = JSON.stringify(canvas.getObjects()); console.log(foo); console.log(bar); } After examining my JSFiddle link above, it appears that JSON.stringify() is al ...

Cordova's Dynamic Scrolling Feature for iOS Overflowing Elements

When using the Safari iOS browser, listening to scroll events triggers the console message every time, even during momentum. However, in the Cordova built app, the message is only triggered when the scroll has stopped. el-with-webkit-overflow-scrolling-to ...

A guide to adding and removing classes with a click event in React

Is there a way to dynamically apply and remove CSS classes on click of multiple div elements (rendered by an array of items) in React? <div onClick={() => { toggleActiveClass(`div${index}`) }} className={(activeDiv === `div${index}`) ? "a ...

Encountering an unexpected token while using square brackets within an object

Eliminating some important details, I have a series of code that leads to an object with properties labeled as prop. Afterward, I set up a $scope.$watch to monitor the changes in the object. Subsequently, the program broadcasts two pieces of data: prop, wh ...

What is the best way to execute multiple testsuites simultaneously with TestCafe, and how can you run a single testsuite

I am facing a situation where I have 6 different test suites that need to be executed. Among them, 5 of the test suites should run with 3 concurrent browsers while the remaining 1 needs to run without any concurrency. Additionally, I want all the results f ...

Nested v-for problem confusion

I am encountering an issue with my code and I'm wondering if anyone can help me troubleshoot it. The problem is that whenever I click on the content of one panel, all panel contents with the same index expand or collapse instead of just the one I clic ...

I would appreciate your assistance with the hide button

Is there a way to hide a button after clicking on it? I would greatly appreciate your help! ...

Using jQuery or JavaScript to clear multiple selections in a multiselect dropdown when a button is clicked

Is there a way to clear the dropdown selections once my function saves data to local storage? You can refer to this fiddle for more details: http://jsfiddle.net/3u7Xj/139/ I already have code in place to handle other form elements: var $form = $("#formI ...

Finding the identifier of an HTML element using AngularJS

I am trying to retrieve the specific id of each line and pass it to a JavaScript function that will make an HTTP request. However, I am encountering an issue when calling the function excluir(id). The parameters seem to be correct, but the alert is not tri ...

What's the reason for Vue alerting me about an endless loop?

Upon using Vue, I encountered a warning message: You may have an infinite update loop in a component render function Although I attempted to resolve the issue by switching from methods to computed properties, the warning persisted. Everything seems to be ...

Animating each individual element within the v-for loop in Vue.JS

Recently, I developed a basic to-do app using VueJS. Additionally, I integrated vue2-animate, which is a Vue.js 2.0 adaptation of Animate.css used for Vue's built-in transitions. The animation feature that adds an element functions correctly. However ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

Changing the li tag by clicking on it is a simple task that can be easily

Whenever I click on a tag, I want the li class to change to "active" and open a new page with the corresponding tag as active. For example, if I click on the Overview tag, the new page should open with the li tag as active. I have attempted to write some c ...

How can I display a badge in my app when it is running using React Native?

For the past week, I've been dealing with an issue. My question is how can I display a new message badge without having to click on the message room when running my app. The badge should only show up after clicking on the message room. I see the badg ...

When it comes to media queries for screen vs. iframe, it is

Currently facing a dilemma. I have a link that appears in an iframe when viewed on a computer, but displays on the parent page if accessed through a mobile device. For mobile users, I want to restrict access to the page only in landscape mode. To achieve ...

JavaScript will not resize the Div element

Although it may seem silly, as this is my profession, I am struggling with some nuances of CSS and JavaScript positioning and sizing. I have a function that animates objects by changing their properties using an easing function. However, each time the ani ...