简体   繁体   English

Express.js | express.Router和路由参数输入

[英]Express.js | express.Router and route parameter input

I have this issue with a little program I'm coding to practice Express.js. 我正在编写一个小程序来练习Express.js,因此遇到了这个问题。

I have a separate router which I want to send a response depending on the route. 我有一个单独的路由器,我想根据路由发送响应。 So if a go to "/santiago", it have to send "Hi Santiago", but right now it sends "Hi undefined". 因此,如果转到“ / santiago”,则必须发送“ Hi Santiago”,但现在它发送“ Hi undefined”。 The code of the router name.js: 路由器name.js的代码:

//name.js
const express = require('express');
const router = express.Router();

router.get('/', (req,res)=>{
    res.send("Hi " + req.params.name);
});

module.exports = router;

And here the code of app.js: 这是app.js的代码:

//app.js
const express = require('express');
const app = express();
let port = process.env.PORT || 3000;
app.listen(port);

const name = require('./name');

app.use('/:name', name);

app.get('/', (req,res)=>{
    res.send("Welcome");
});

What is wrong? 怎么了?

Your router doesn't get the parameter. 您的路由器未获取参数。 Set the parameter on your name.js (router): 在您的name.js(路由器)上设置参数:

router.get('/:name', (req,res)=>{
    res.send("Hi " + req.params.name); 
});

And your root route on server.js: 而您在server.js上的根路由:

app.use('/', name);

Basically your router will be called on root but expect a parameter. 基本上,您的路由器将在root上被调用,但是需要一个参数。

This should fix your issue and 'Welcome' will still be printed on root. 这应该可以解决您的问题,“欢迎”字样仍会显示在根目录上。 This is because the router expects a parameter so if not, your last app.get method will run. 这是因为路由器需要一个参数,因此,如果没有,则将运行您的最后一个app.get方法。

Hope that helps ! 希望能有所帮助!

You need to mark the param in the route. 您需要在路线中标记参数。 Try something like this: 尝试这样的事情:

app.get('/:name', (req,res) => {
    const { name } = req.params
    res.send("Hi " + name)
});

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

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