2015-06-01 18 views
1

我收到來自Mailgun的解析電子郵件,通過它們的API發佈到我設置的URL終點。接收HTTP帖子的URL是使用body parser中間件到MongoDB的Expressjs路由。我有一個簡單的文本鍵,像'發件人',但我有一些包含連字符的消息參數的格式問題的路徑工作正常的MongoDB的http後。例如「身體素質」。如果我包含「req.body.body-plain」的參數,則Express會引發錯誤。有沒有人有工作?Express JS路由器中間件 - 正文解析器 - req.body有連字符

我不想正則表達整個字符串。

這是張貼在電子郵件響應的例子:

recipient: '[email protected]', 
    sender: '[email protected]', 
    subject: 'tewsgs', 
    from: 'Kevin Psdit <[email protected]>', 
    'X-Envelope-From': '<[email protected]>', 
'body-plain': 'this is a test\r\n', 
    Received: 
    [ 'from mail-qk0-f179.google.com (mail-qk0-f179.google.com   [209.85.220.179]) by mxa.mailgun.org with ESMTP id 556bfda1.7f7658358ef0- in01; Mon, 01 Jun 2015 06:37:21 -0000 (UTC)', 
'by qkx62 with SMTP id 62so79143349qkx.3 for <[email protected]>; Sun, 31 May 2015 23:37:21 -0700 (PDT)', 
'by 10.140.18.241 with HTTP; Sun, 31 May 2015 23:37:21 -0700 (PDT)' ], 
    'Dkim-Signature': 'v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com;  s=20120113; h=mime-version:date:message-id:subject:from:to:content-type; cdx2K5lDwCjwcy0S6407m6/q9tAnFIltsT48O1nCACzQ4RQQYiXa VuiA==', 
'Mime-Version': '1.0', 
    'X-Received': 'by 10.55.23.130 with SMTP id 2mr35323631qkx.33.1433140641295; Sun, 31 May 2015 23:37:21 -0700 (PDT 
)',Date: 'Sun, 31 May 2015 23:37:21 -0700' 

這裏是快遞路線:

'use strict'; 

var mongoose = require('mongoose'); 
var Email = mongoose.model('Email'); 

module.exports = function(router) { 

router.route('/emails') 
    //creates a new email 
    .post(function(req, res){ 
     var email = new Email(); 

//THESE WORK 
    email.recipient = req.body.recipient; 
    email.sender = req.body.sender; 
    email.from = req.body.from; 
    email.subject = req.body.subject; 
    email.timestamp = req.body.timestamp; 
    email.token = req.body.token; 
    email.signature = req.body.signature; 

//THESE DO NOT WORK BECAUSE OF HYPHEN IN NAME 
    email.body_plain = req.body.body-plain; 
    email.stripped_text = req.body.stripped-text; 
    email.stripped_signature = req.body.stripped-signature; 
    email.body_html = req.body.body-html; 
    email.stripped_html = req.body.stripped-html; 
    email.attachment_count = req.body.attachment-count; 
    email.attachment_x = req.body.attachment-x; 
    email.message_headers = req.body.message-headers; 
    email.content_id_map = req.body.content-id-map;  

email.save(function(err, email) { 
    if (err){ 
    return res.send(500, err); 
    } 
    return res.json(email); 
}); 
    }) 

回答

5

的解決方法是使用括號記號,這樣你可以訪問關鍵的是有點符號無效的字符

req.body['body-plain'] 
+0

感謝您的快速回答。 –