我目前正试图从特定路线规则中的表单中捕获已发布的值。 由于关于此的所有其他SO帖子都不起作用,我想再问一次。你有没有在你的项目中整理和实施? 有没有针对Iron-Router@1.0.9的解决方案?
this.request.body
路由规则中的上述代码始终返回undefined。
Router.route('/register', function(){
console.log( JSON.stringify(this.request.body) );
//this.render('test',{data:{data:this.request.body.username}})
});
//SERVER ONLY
if (Meteor.isServer) {
Meteor.methods({
'addSong': function(songName) {
var userId = Meteor.userId()
songs.insert({
userId: userId,
name: songName
})
}
})
Router.onBeforeAction(Iron.Router.bodyParser.urlencoded({
extended: true
}));
}
答案 0 :(得分:0)
this.request
和this.response
是“NodeJS请求和响应对象”的铁路由器指南lets us know。
如果你看一下req.body
的一些文档,你会发现:
默认情况下,它是未定义的,并在您使用时填充 身体解析中间件,如body-parser和multer。
IR在Iron.Router.bodyParser上提供了表达'body-parser。
所以你有它!如果您想要填充this.request.body
,您应该添加:
Router.onBeforeAction(Iron.Router.bodyParser.urlencoded({
extended: true
}));
答案 1 :(得分:0)
我为控制器创建了一个文件,以在控制器文件夹下维护代码可重用性名称为solar.js,即solar文件具有我的db功能,并将请求和响应作为该文件的参数传递,例如export.getSolarInfo =(req ,res)=> {console.log(req.body)},在这里您将获得您的参数。然后在此处操作我们的功能,然后发送响应,例如response = {“ status”:0,“ result”:“ invalid query” } res.end(JSON.stringify(response));
//导入控制器 const SOLAR = require('./ controllers / solar.js');
Router.route( '/solar', function() {
//setting header type to allow cross origin
this.response.setHeader( 'Access-Control-Allow-Origin', '*' );
if ( this.request.method === "OPTIONS" ) {
this.response.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' );
this.response.setHeader( 'Access-Control-Allow-Methods', 'POST, PUT, GET, DELETE, OPTIONS' );
this.response.end( 'Set OPTIONS.' );
} else {
SOLAR.getSolarInfo(this.request,this.response);
}
}, { where: 'server' });