在Postman中使用form-data时,结果未定义

时间:2015-10-20 08:50:58

标签: node.js post postman form-data

我可以在postman插件中使用x-www-form-urlencoded选项卡获得结果但是我希望从chrome中邮递员插件的form-data选项卡中获取结果。



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 个答案:

答案 0 :(得分:2)

您正在使用的代码,解析application/x-www-form-urlencoded,而通过邮递员中的表单数据标签发布的内容为multipart/form-data

使用强大的 https://www.npmjs.com/package/formidable

添加此

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

这用于文件上传或者你有很多参数,在你的情况下它没有用

简而言之,只需使用x-www-form-urlencoded标签:D