如何在app.get中访问变量或变量集并使整个项目可以访问?我试图捕获从SMS文本发送的信息,组织成“messageData”变量,然后发送到“MessageSchema”,然后将其发送并存储在Mongo数据库中。我的问题是,我相信没有找到任何变量(消息,数字,答案)。我该如何解决这个问题?
app.js
app.get('/smssent', function(req, res, callback) {
var message = req.query.Body;
var number = req.query.From;
var twilioNumber = req.query.To;
var context = null;
var index = 0;
var contextIndex = 0;
contexts.forEach(function(value)
{
console.log(value.from);
if (value.from == number)
{
context = value.context;
contextIndex = index;
}
index = index + 1;
});
console.log('Recieved message from ' + number + ' saying \'' + message + '\'');
var conversation = new ConversationV1({
username: '',
password: '',
version_date: ConversationV1.VERSION_DATE_2016_09_20
});
//console.log(JSON.stringify(context));
//console.log(contexts.length);
conversation.message({
input: { text: message },
workspace_id: '',
context: context
}, function(err, response) {
if (err) {
console.error(err);
} else {
var answer = response.output.text[0];
if (context == null) {
contexts.push({'from': number, 'context': response.context});
} else {
contexts[contextIndex].context = response.context;
}
var intent = response.intents[0].intent;
console.log(intent);
if (intent == "done") {
//contexts.splice(contexts.indexOf({'from': number, 'context': response.context}),1);
contexts.splice(contextIndex,1);
// Call REST API here (order pizza, etc.)
}
var client = require('twilio')(
'',
''
);
client.messages.create({
from: twilioNumber,
to: number,
body: response.output.text[0]
}, function(err, message) {
if(err) {
console.error(err.message);
}
});
}
});
res.send('');
});
(ABOVE)这是检索SMS文本,并执行Twilio,Node和IBM Bluemix的内容。
index.js
router.post('/app', function(req, res, next) {
if (req.body.number &&
req.body.message &&
req.body.answer
) {
// create object with form input
var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
// use schema's `create` method to insert document into Mongo
Message.create(messageData, function (error, message) {
if (error) {
return next(error);
} else {
return res.redirect('/');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
});
(ABOVE)这是为“MessageSchema”组织和准备一切的代码。
message.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var MessageSchema = new mongoose.Schema({
number: {
type: String,
required: true,
trim: true
},
message: {
type: String,
required: true,
trim: true
},
answer: {
type: String,
required: true,
trim: true
}
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
最后,这是将所有信息发送到数据库的内容。
如果有人发现任何内容或有任何改进此代码的提示,请告诉我,我愿意为您提供所有输入!
谢谢!
答案 0 :(得分:0)
var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
这没关系。但是,请记住,这些变量是通过POST主体发送的,而不是像其他查询一样发送的。
queries: ?param = ...
body: (like POST form; hidden from the URL)
如果您不确定自己是否正常传递,可以通过console.info(...)
在某一点轻松测试;并使用Postman轻松测试POST行为。