req.body.variablename在使用body-parser中间件的express中是未定义的

时间:2018-02-21 12:27:13

标签: node.js express body-parser

我在Nodejs应用程序中使用express 4.14.1版本。我也使用正文解析器中间件来解析表单数据但是当我编写console.log(req.body.variablename)时,我在控制台上得到了未定义。 我的代码如下

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser'); //parses information from POST
const request = require('request');
const mongodb = require('../model/mongodb.js');
const smtpTransport = require('../model/mailer.js');
const Agent = require('../model/agentmodel.js');
const config = require('../config.js');
const intent = require('../intents.js');
const ejs = require('ejs');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// use res.render to load up an ejs view file
router.get('/chat', function(req,res){
    // res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
    res.render('pages/index', { heading: config.property.userheading});         
});

// use res.render to load up an ejs view file
router.get('/', function(req,res){
  // res.sendFile(path.join(__dirname + '/html/' + '/index.html'));
  res.render('pages/helpdesk');       
});

router.post('/createTicket', function(req,res){
  console.log("create ticket is called from email support");
  console.log(req.body);
  console.log("and the details as follows ==>");
  console.log("username is ==> "+req.body.userName);
  console.log("message is ==>"+req.body.message);
  var json = {
          name :   req.body.userName,
          email :  req.body.userEmail,
          subject: 'Demo Subject',
          message:  req.body.message,
          topicId : req.body.topicId,
        };

        var options = {
          url: 'http://domainname/iprhelpdesk/upload/api/http.php/tickets.json',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key' : 'API-key'
      },  
      json:json
    };

   request(options, function(err, res, body) {
     if (res && (res.statusCode === 200 || res.statusCode === 201)) {
       console.log("response is ==>");
       console.log(res);
     }
     else {
      console.log("error is "+err+ " = and reponse code is ="+res.statusCode );
     }
    });
   res.render('pages/message');   
});

以下是控制台的输出

  通过电子邮件支持调用

创建故障单{   ' {" topicId":{" Id":12," name":" Basic IPR Query"},&#34 ;消息":"我想   了解ipr"," userName":" Pawan   帕蒂尔""国家":" IN"" USEREMAIL":" pawanpatil.rocks@gmail.com",&#34 ;接触":" 09665714555"}&#39 ;:   '' }和详细信息如下==>用户名是==>未定义的消息   是==>未定义POST / createTicket 200 21.161 ms - 104错误为null =   和响应代码是= 400

这就是chrome作为表单数据发送的内容

  

{" topicId":{" Id":12," name":" Basic IPR Query"},"消息":"我想   了解ipr"," userName":" Jon   雪""国家":" IN"" USEREMAIL":" test@test.com","&接触#34;:" 0123456789"}:

请求标头是

  

内容类型:应用/ X WWW的窗体-urlencoded

一切似乎都很完美,但我仍然是

  

未定义

当我编写console.log时("用户名为==>" + req.body.userName);在我的代码中。 请帮帮我

2 个答案:

答案 0 :(得分:2)

我已经解决了改变

的问题
  

内容类型:应用/ X WWW的窗体-urlencoded

标题为

  

Content-Type:application / json

答案 1 :(得分:1)

移动那些:

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

在此之前:

app.use(app.router)

所以你的bodyParser需要在路由器之前进行初始化。我也读过这个:

app.use(require('connect').bodyParser());

Insted of:

app.use(express.bodyParser());

也可以使用未定义的req.body

解决问题

还有一件事要尝试:

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

extended设为false而不是true