简体   繁体   English

如何解决无法读取express js中未定义的属性“名称”?

[英]how to solve Cannot read property 'name' of undefined in express js?

I'm not able to perform the routing with the parameter, I'm getting the error cant read property 'name' .我无法使用参数执行路由,我收到错误cant read property 'name' I used the template engine twig .我使用了模板引擎twig Here is my template,这是我的模板,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{About}}</title>
</head>
<body>
   <P><h1>{{user}}</h1></P>
   <P><h2>{{text}}</h2></P>
</body>
</html>

this is my main 'js' file-这是我的主要“js”文件-

const express=require('express')
const app=express()

app.use('./static',express.static('twig templet'))
app.set('view engine', 'twig')
app.set('views','./twig templet/views')

app.get('/',(res,req)=>{
    req.render('index',{title:'EXPRESS',gred:'Hello-welcome to Express',mes:'This is twig file'})

})

app.get('/about/:name',(res,req)=>{
    res.render('about',{About:'User',user:req.params.name,text:'This is twig file'})
    console.log('user is:'+ req.params.name)
 
})

app.get('/calculation/:a-:b',(res,req)=>{
    res.render('calculator',
    {About1:'Calculation',
    add:parseInt(req.params.a) + parseInt(req.params.b),
    sub:parseInt(req.params.a) - parseInt(req.params.b),
    mul:parseInt(req.params.a) * parseInt(req.params.b),
    div:parseInt(req.params.a) / parseInt(req.params.b)})


    //console.log('user is:'+ res.params.Name)

})

app.listen(5000,()=>{
    console.log("server is running at 5000")
})

You have the callback values from the app.get() in the wrong order, it should be like this, you can omit the next though,你有来自 app.get() 的回调值顺序错误,应该是这样的,你可以省略next

app.get('/about/:name',(req, res, next) => {}

That's it.就是这样。

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

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