Result is undefined when I use form-data in Postman

房东的猫 提交于 2019-12-24 12:34:09

问题


I can get the result using x-www-form-urlencoded tab in postman plug-in but case i want to get it from the form-data tab in the postman plug-in in the the chrome.

var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var Random = require("random-js")();

app.use(bodyParser());
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 

app.post('/TransactionDelay', function(req, res) {

  var SecurityToken=req.body.SecurityToken;
  var SessionID=req.body.SessionID;
  var TimeStamp=Date.now();
  var SecretTransactionKey=req.body.SecretTransactionKey;
  var TransactionID=req.body.TransactionID;
  var BanksTransactionRefID=req.body.BanksTransactionRefID;
  var SessionRequestType=req.body.SessionRequestType;
  var StatusCode=req.body.StatusCode;
  var StatusDescription=req.body.StatusDescription;
  var tag=req.body.tag;

  var dataFile={"SecurityToken":SecurityToken,"SessionID":SessionID,"TimeStamp":TimeStamp,
  "SecretTransactionKey":SecretTransactionKey,"TransactionID":TransactionID,"BanksTransactionRefID":BanksTransactionRefID,
  "SessionRequestType":SessionRequestType,"StatusCode":StatusCode,"StatusDescription":StatusDescription,
  "Tag":tag};

  res.send('TimeStamp : '+dataFile.TimeStamp+'\nTransactionID : '+dataFile.TransactionID+'\nReplyId : 12993784\nStatusCode : '+dataFile.StatusCode+'\nStatusDescription : '+dataFile.StatusDescription+'\nTags :'+dataFile.Tag);

});

 function checkStatusCode(){
  var status=["Confirmed","Failed","Pending"];
  return status[Random.integer(0,2)];
 }
app.listen(port);
console.log('Server started! At http://localhost:' + port);

回答1:


The code you're using, parses application/x-www-form-urlencoded, whereas what's being posted is multipart/form-data via form-data tab in postman

Use formidable https://www.npmjs.com/package/formidable

add this

var formidable = require('formidable');
var util = require('util');
app.post('/TransactionDelay', function(req, res) {
    var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        res.write('received upload:\n\n');
        res.end(util.inspect({
            fields: fields,
            files: files
        }));
    });
}

this is used for file upload or u have a lot of parameters , in ur case it's not useful

In short just use x-www-form-urlencoded tab :D



来源:https://stackoverflow.com/questions/33232086/result-is-undefined-when-i-use-form-data-in-postman

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!