【问题标题】:Issues with my simple restfull api : No rawBody in body-parser and .delete expression not working?我简单的 api 的问题:body-parser 中没有原始 Body 和 .delete 表达式不起作用?
【发布时间】:2015-12-24 15:30:35
【问题描述】:

我正在使用 express4、mongoose 和 body 解析器作为中间件构建一个简单的 restful API。

索引.js

//base setup
var express = require('express'); // call express
var mailsystem = express(); // define our app using express
var bodyParser = require('body-parser');
var InDb = require('./mailsystem/client/clientsend');
var mangoose = require('mongoose');
var morgan = require('morgan');
mailsystem.use(morgan('dev'));
// require('daemon')();

mangoose.connect('mongodb://abc:abc@ds031982.mongolab.com:31982/mailsystem2');

// configure app to use bodyParser()
// this will let us get the data from a POST
mailsystem.use(bodyParser.urlencoded({
  extended: true
}));
mailsystem.use(bodyParser.json());

mailsystem.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) {
    req.rawBody += chunk;
  });

  req.on('end', function() {
    next();
  });
});

var port = process.env.PORT || 8080; // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router

router.use(function(req, res, next) {
  console.log('inside route');
  next();
});
router.route('/clietsends')

.post(function(req, res, next) {


    //req.rawBody ='';
    //req.setEncoding('utf-8');
    // var mine;
    //var contentType = req.headers['content-type'] || '', mime = contentType.split(';')[0];


    var clientsend = new InDb();
    //clientsend.name = req.body.name;
    clientsend.emailId = req.body.emailId;
    clientsend.subject = req.body.subject;
    clientsend.message = req.body.message;
    var email = clientsend.emailId;
    var sub = clientsend.subject;
    var mess = clientsend.message;
    //Call_mandrill(email, sub, mess);
    console.log(req.body);
    console.log(req.params);
    clientsend.save(function(err) {
      if (err)
        res.send(err);
      else {
        req.body += req.rawBody;
        //req.rawBody += req.params;
        res.json(req.body);
        //console.log(req.params);
      }

      // res.json({message:'message of post created'})
    });
  })
  .get(function(req, res) {
    //need not to initiliaze again
    /*var clientsend = new InDb();
    clientsend.name = req.body.name;
    */
    InDb.find(function(err, clientsend) {
      if (err)
        res.send(err);

      res.json(clientsend);
    });
  });

router.route('/clietsends/:clietsend_id')
  .get(function(req, res) {

    InDb.findById(req.params.clietsend_id, function(err, clientsend) {
      if (err)
        res.send(err);
      res.json(clientsend);
    });
  })
  .put(function(req, res) {

    InDb.findById(req.params.clietsend_id, function(err, clientsend) {

      if (err)
        res.send(err);
      clientsend.emailId = req.body.emailId;
      clientsend.subject = req.body.subject;
      clientsend.message = req.body.message;

      // save the update 
      clientsend.save(function(err) {
        if (err)
          res.send(err);
        res.json(req.body);
        //res.json({ message: 'client updated!' });
      });

    });
  })

.delete(function(req, res) {
  InDb.remove({
    _id: req.params.clietside_id
  }, function(err, clientsend) {
    if (err)
      res.send(err);
    //var m = req.body;
    delete req.params.clietsend_id;
    console.log(req.params.clietsend_id);
    res.json({
      message: 'Successfully deleted'
    });
  });
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
  res.json({
    message: 'add /clietsends to view all'
  });
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
mailsystem.use('/testapi', router);

// START THE SERVER
// =============================================================================
mailsystem.listen(port);
console.log('open port' + port);


//function mandrill
// =============================================================================
function Call_mandrill(email, sub, mess) {
  var mandrill = require('mandrill-api/mandrill.js');

  function log(obj) {
    //$('#response').text(JSON.stringify(obj));
    console.log(JSON.stringify(obj));
  }
  var m = new mandrill.Mandrill('9VUmdqbiZFiLCev4C_8Q6A');
  // LOOK HERE TO CHANGE FROM EMAIL ID
  //========================================
  var params = {
    "message": {
      "from_email": "noreply@signzy.com",
      "to": [{
        "email": email
      }],
      "subject": sub,
      "text": mess,
      "autotext": true,
      "track_opens": true,
      "track_links": true
    }
  };

  function sendTheMail() {

    m.messages.send(params, function(res) {
      log(res);
    }, function(err) {
      log(err);
    });
  }

  function run() {
    sendTheMail();
    return false;
  }
  run();

}

和 mailsystem/client/ 中的 clietsend.js

// mailsystem/client/clientside.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var SendSchema = new Schema({
  emailId String, 
  subject String,
  message String 
});

module.exports = mongoose.model('Sent', SendSchema);

一切正常,除了我有 2 个我无法弄清楚的问题:

1) 正文/输入的形式为 xxx-urlencoded 我希望它是原始的,所以通过this post 并对我的代码进行了更改,因为您可以在 cmets 中看到它们,但它们似乎不起作用.我究竟做错了什么?有人可以举个例子吗?

2) .delete 函数返回 json 对象但不删除它。不知道为什么 PUT、PUSH、GET 似乎工作正常。

在 jakerela 建议做出相应更改后,但问题出在 res.json(reqbody) 上,在我想要一个 json 对象的地方返回了一个字符串,并且还返回了类似“[object object]”之类的内容

【问题讨论】:

    标签: javascript node.js rest express


    【解决方案1】:

    看起来您实际上并没有按照其他帖子中的说明进行操作。正文解析器根本不提供原始正文数据,而是您必须自己使用 Express 中间件您的路由和使用 Streams 来实现它。

    在您的其他路线(可能是第 19 行)之前添加此代码:

    app.use(function(req, res, next) {
      req.rawBody = '';
      req.setEncoding('utf8');
    
      req.on('data', function(chunk) { 
        req.rawBody += chunk;
      });
    
      req.on('end', function() {
        next();
      });
    });
    

    您可以从其他路由中访问req.rawBody

    【讨论】:

    • 嘿@jakerella 非常感谢我改变了你所说的东西,但不知何故我什么时候做 res.json(req.body) 在这里我得到一个字符串而不是一个 json 对象,在那一行之前我添加 req.body += req.rawBody;我究竟做错了什么 ?我已经用新代码更新了帖子,请检查一下。
    【解决方案2】:

    好吧,我想通了,上面的代码根本不需要任何 rawBody,只是在标题中添加了内容类型,它工作正常。 当我使用邮递员时,只需导航到标题并添加应该工作的内容类型。 或者您也可以在代码中添加一行以使其正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2021-02-05
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2021-10-10
      相关资源
      最近更新 更多