问题描述
这是路线代码:
router.get('/compose/:ID',function(req,res,next) {
var random = Math.floor((Math.random() * 1000000) + 1);
console.log("random = " + random);
res.render('compose',{ random: random,Id:req.params.ID });
})
.post(function(req,next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
console.log(text);
nexmo.message.sendSms(from,to,text,function(err,success){
if(success)
console.log("SMS sent successfully!");
else {
console.log("error");
}
});
});
这是车把代码:
<main role="main" class="container">
<div class="jumbotron">
<h1>List of Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form method="post" enctype="multipart/form-data">
<tr>
<td><input type="text" name="OTP" class="form-control" value="Hi. Your OTP is : {{random}}"></td>
<td></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</td>
</tr>
</form>
</tbody>
</table>
</div>
</main>
它已到达路线,但控制台未打印“文本”。 aka console.log(text)
表示req.body.OTP
没有打印任何内容。之前它是未定义的。
您能纠正可能卡在哪里的问题吗?
解决方法
您遇到的问题是body-parser
无法解决multipart/form-data
。
有几种选择,但其中一种是multer
。
\* add these for multi-part*\
var multer = require('multer')
var upload = multer();
\* other code *\
router
.get('/compose/:ID',function (req,res,next) {
var random = Math.floor(Math.random() * 1000000 + 1);
console.log('random = ' + random);
res.render('compose',{ random: random,Id: req.params.ID });
})
.post('/compose/:ID',upload.none(),next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
nexmo.message.sendSms(from,to,text,function (err,success) {
if (success) console.log('SMS sent successfully!');
else {
console.log('error');
}
});
});