问题
I would like to know how to pass parameters when using the official webapp package to listen to incoming HTTP requests on a particular route.
Here is an example code:
WebApp.connectHandlers.use("/hello/:myParam", function(req, res, next) {
res.writeHead(200);
res.end("Your param is", req.myParam);
});
The above Express-like example does not work with WebApp. After some experiments, I now know I can access query params using req.query
. But does WebApp allow you to access regular parameters?
回答1:
I don't know of a connect middleware that does that (it might exist though, in which case you could plug it in), but it's easy enough to replicate that behavior:
WebApp.connectHandlers.use("/hello/", function(req, res, next) {
var parts = req.url.split("/");
res.writeHead(200);
res.end("Your param is " + parts[1]);
});
Not quite the same but seems to work well. Of course, most people would just use iron-router for something like this, but I'm assuming you want to avoid that for some reason.
回答2:
I know this question is more than 1 year old, but there seems to be no built-in method yet, so here's how I did it. There is an npm package called connect-route (I'm almost sure there are others). Install it with npm i --save connect-route
. Then in your code:
import connectRoute from 'connect-route';
WebApp.connectHandlers.use(connectRoute(function (router) {
router.get("/post/:id", function(req, res, next) {
console.log(req.params); // { id: 1 }
res.writeHead(200);
res.end('');
});
router.get("/user/:name/posts", function(req, res, next) {
// etc. etc.
});
}));
Works like a charm for me with version 0.1.5
回答3:
Straight out of the box, you can use query instead of Params like you do in express. There's no real downside other than URL personal preference for using Parameters instead of Query.
Here's an example, providing a PDF from a route using connectHandlers:
WebApp.connectHandlers.use("/billPreview", function(req, res, next) {
var re = urlParse.parse(req.url, true).query;
if (re !== null) { // Only handle URLs that start with /url_path/*
// var filePath = process.env.PWD + '/.server_path/' + re[1];
console.log('Re: ',re);
var filePath = process.env.PWD + '/.bills/pdf/' + re.id +'/'+re.user+'/lastTicket.pdf';
var data = fs.readFileSync(filePath, data);
res.writeHead(200, {
'Content-Type': 'application/pdf'
});
res.write(data);
res.end();
} else { // Other urls will have default behaviors
next();
}
});
来源:https://stackoverflow.com/questions/33048610/meteor-webapp-middleware-passing-params