简体   繁体   中英

400 bad request Ajax post via CLI

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);
        });
    }

Simple video reqirements

You can use node to do this. Have you tried using something like FS?

This answer was originally posted here Write to a CSV in Node.js

You can use fs ( 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('Some error occured - file either not saved or corrupted file saved.');
  } else{
    console.log('It\'s saved!');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM