2

I've got the following code in Python:

import requests
fileslist = [('file[]',('user_query.txt', open('user_query.txt', 'rb'), 'text/plain')),
                ('file[]',('wheatData.csv', open('wheatData.csv', 'rb'), 'text/csv')),]

r = requests.post('url',
    files=fileslist)

And I'm trying to convert it to a node.JS version. So far I've got this:

var request = require('request');
var fs      = require('fs');

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log(body);
  }
});

var form = req.form();
form.append('wheatData.csv', fs.createReadStream('wheatData.csv'));
form.append('user_query.txt', fs.createReadStream('user_query.txt'));

What am I doing wrong?

foxes
  • 808
  • 1
  • 7
  • 13
  • Did you get an error and if so what exactly is the error? – Jason Livesay Apr 05 '16 at 05:29
  • Well I changed the file names at the beginning of `form.append` to `file[]` and now my backend tells me that I haven't uploaded the correct number of files (which is two). – foxes Apr 05 '16 at 20:12

1 Answers1

1

This is how you do it using express and body-parser module to parse the post request and fetch the files you need .This is what goes in your node.js server.

Import all the modules :

var express = require("express");
var bodyParser = require('body-parser')
var app = express(); //init express app()
var util = require('util');

//APP CONFIGURATION >> Skip this if you dont want CORS
app.use(express.static('app')); // use this as resource  directory
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

Configure the post Url :

//url => url/for/mypostrequest
app.post(url, done, function (req, res) {

    //Handle the post request body here...
    var filesUploaded = 0;
    //check if files present
    if (Object.keys(req.files).length === 0) {
        console.log('no files uploaded');
    } else {
        console.log(req.files);
        var files = req.files.file1;
        //If multiple files store in array..
        if (!util.isArray(req.files.file1)) {
            files = [req.files.file1];
        }
        filesUploaded = files.length;
    }
  res.json({message: 'Finished! Uploaded ' + filesUploaded + ' files.  Route is /files1'});
});

Make sure all the modules are installed and present as dependencies in package.json


CODE for making an api post call from node..

Include the http module first in your server .

var http = require('http');
var querystring = require('querystring');
var fs = require('fs');

Theninclude following code to make a post request from node server

    var file1, file2;
    //Read first File ...
    fs.readFileSync('wheatData.csv', function (err, data) {
        if (err) {
            console.log('Error in file reading...');
        }
        file1 = data;

        //Read second file....
        fs.readFileSync('wheatData.csv', function (err, data) {
            if (err) {
                console.log('Error in file reading...');
            }
            file2 = data;

            //Construct the post request data..
            var postData = querystring.stringify({
                'msg': 'Hello World!',
                'file1': file1,
                'file2': file2
            });
            var options = { //setup option for you request
                hostname: 'www.path/to/api/',
                port: 80,
                path: '/upload',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': postData.length
                }
            };
            var req = http.request(options, function (res) {
                console.log('STATUS:' + res.statusCode);
                console.log('HEADERS:' + JSON.stringify(res.headers));
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    console.log('BODY: ' + chunk);
                });
                res.on('end', function () {
                    console.log('No more data in response.');
                });
            });
            req.on('error', function (e) {
                console.log('problem with request: ' + e.message);
            });
            // write data to request body
            req.write(postData);
            req.end();

        });
    });

Please note that code has not been tested on live server , you may need to make alteration as per your configuration.

Also you can use other libraries like request or needler..etc to make post calls from node server as suggested in this post.

Community
  • 1
  • 1
damitj07
  • 2,689
  • 1
  • 21
  • 40
  • Well it's for a uni assignment where we have to create an API, and we've created one in Python and been testing making API calls in Python to it - is it possible for a node.JS script to call our API without putting node.JS in the backend? – foxes Apr 05 '16 at 20:10
  • you can use [http](https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_http_request_options_callback) module of node.... to make api call from inside the node... I have added sample code in answer update ... And about node.js not being in backend that depends on to what extent you want node.js in you application. you can either use it as lightweight server for serving html or as a service layer API. It is entirely your decision. – damitj07 Apr 06 '16 at 05:38
  • I'm not sure if you're understanding me properly - we're not using node.JS at all in our backend, we're using Python/Flask. But if another classmate happened to be wanting to call our API, and their project was in node.JS, would they be able to do that? – foxes Apr 07 '16 at 00:02
  • Yes they can and the code posted above is for same thing – damitj07 Apr 07 '16 at 02:45