Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the values from postman extention "form-data" values

Tags:

node.js

I am using node js with express framework and rest api for rest api client i am using postman extension with chrome browser here i am able to get values from option "x-www-form-urlencoded" but i am not able to get values from "form data" i want to get values from "form data" option and also need to upload image file. please help me any to achieve this. i want to get values from "form data" option and also image. please help me. Below i have mentioned code what i have used. enter image description here

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var http = require('http').Server(app);
var mysql = require('mysql');
var util = require('util');
var trim = require('trim');
var validator = require('validator');
var bodyParser = require('body-parser');
var Ingest      = require('ingest');
var multer      = require('multer');
var upload = multer({ dest: 'uploads/' });
var type = upload.single('recfile');
 passport = require('passport')
 , LocalStrategy = require('passport-local').Strategy;

async = require('async');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ 
   extended: true 
}));

app.post('/upload', function(req, res){
    console.log(req.file); // "form-data" values not able to get here
    console.log(req);// "form-data" values not able to get here
    console.log('body : '+JSON.stringify(req.body));// "form-data"  values not able to get here
});

i didn't set any content type in postman header

app.post('/upload', function(req, res){
    console.log('req.headers \n '+JSON.stringify(req.headers));     
    console.log('req.body.file :- '+req.body.file);
    console.log('\n\n req.body :- '+JSON.stringify(req.body));
});

I got the below result for the above code. req.headers

 {"host":"localhost:3001","connection":"keep-alive","content length":"5808","cache-control":"no-cache","origin":"chrome-extension://mkhojklkhkdaghjjfdnphfphiaiohkef","password":"password","user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36","username":"User2","content-type":"multipart/form-data; boundary=----WebKitFormBoundaryV4zAIbjEyKYxLRWe","accept":"*/*","accept-encoding":"gzip, deflate","accept-language":"en-US,en;q=0.8","cookie":"connect.sid=s%3Atz4f1ZgJkaAjuDD1sOkMB9rr.Z8EUIyxEcr0EyFQL96v0ExGRidM3SAVTx8IIr52O0OI"}

req.body.file :- undefined

req.body :- {}

like image 585
raj Avatar asked Mar 29 '16 05:03

raj


People also ask

How can I get Postman form-data?

To send a POST request, select the POST request method, click on Body, and select form-data. If you look at the response body, you will notice that the data you have submitted.


2 Answers

Yes the same problem facing me several times and according my experience you do't set the content-type in postman header because it should be undefined and node server automatically set the content type according to requirement. If you set the content-type then you do't get any image and other data in the node server .

  1. You get the image from the req.body.file
  2. you get the other data from req.body
  3. app.use(multipart()) in middleware

Procedure how to use multipart as middleware

  1. var multipart = require('connect-multiparty');
  2. global.app = module.exports = express();
  3. app.use(multipart());
like image 96
Himanshu Goyal Avatar answered Oct 06 '22 15:10

Himanshu Goyal


I got solution with help of the below code

    var express = require('express');
    var router = express.Router();
    var util = require("util"); 
    var fs = require("fs");
    var formidable = require('formidable');
    var path = require('path');

    router.post("/upload", function(req, res, next){ 
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // `file` is the name of the <input> field of type `file`
        console.log(files);
        console.log(fields);
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    form.on('error', function(err) {
        console.error(err);
    });
    form.on('progress', function(bytesReceived, bytesExpected) {
        var percent_complete = (bytesReceived / bytesExpected) * 100;
        console.log(percent_complete.toFixed(2));
    });
    form.on('end', function(fields, files) {
        /* Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /* The file name of the uploaded file */
        var file_name = this.openedFiles[0].name;
        /* Location where we want to copy the uploaded file */
        var new_location = 'public/images/';

        fs.readFile(temp_path, function(err, data) {
            fs.writeFile(new_location + file_name, data, function(err) {
                fs.unlink(temp_path, function(err) {
                    if (err) {
                        console.error(err);
                        } else {
                        console.log("success!");
                    }
                });
            });
        });
    });
});
like image 32
raj Avatar answered Oct 06 '22 15:10

raj