简体   繁体   English

使用不同参数的ExpressJS路由

[英]ExpressJS routing with different parameters

I have two routes : app.use serves the static files. 我有两条路线:app.use提供静态文件。

 app.use('/test', earlyAccess(), express.static(path.join(__dirname, staticFolder)))

app.get("/test", callback);
app.get("/test/:id", callback);

// Here is the callback
var fileStream = fs.createReadStream(staticFolder + '/test.html');
fileStream.on('open', function () {
  fileStream.pipe(res);
});

From the browser, if I call localhost:80/test/1 - works fine. 从浏览器,如果我调用localhost:80/test/1可以正常工作。 but if I call localhost:80/test - it gets redirected to main page. 但是如果我调用localhost:80/test它会重定向到主页。 In the server console, I got 304 warning. 在服务器控制台中,我收到304警告。

How to use routes based on parameter in expressjs? 如何在expressjs中使用基于参数的路由?

尝试使用res.sendFile代替fs.createReadStream ,类似于:

res.sendFile('test.html');

You can check for request parameters within the callback, 您可以在回调中检查请求参数,

app.get('/test', callback);
app.get('/test/123', callback);

// callback
if(req.params.second) {
  // code for route with param. - /test/123
}
else {
// code for route without param. - /test
}

Parameters in the request are stored in req.params as 请求中的参数存储在req.params中,格式为

{first:'NameOfRoute', second:'NextParam'} ...

So here, 所以在这里,

{first:'test', second:'123'}

you can try it like this: 您可以这样尝试:

app.use("/test/*", (req, res, next) => {
   // your callback(req, res);
   next();
});
app.get("/test/:id", callback);

app.use , mean you can write a middleware, and it will call next(); app.use ,意味着您可以编写一个中间件,它将调用next() app.use

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM