weixin_33670713 2015-06-27 20:21 采纳率: 0%
浏览 71

复杂的node.js网址映射

I need help in url mapping in express.js framework in nodejs.

router.get('/first/:second_param', function(res,req){
    //processing second_param and rendering a template,
res.render('first.html');
});

router.get('/first/:second_param/get_items', function(res,req){
    //again evaluating second_param and and responding accordingly
res.send(jsonData);
});

Is this kind of routing possible in Express 4.0?

first.html makes a ajax request at url './get_items'

  • 写回答

1条回答 默认 最新

  • weixin_33716557 2015-06-27 21:49
    关注

    Yes, it is possible to do it with Express 4.0.

    Here is an example:

    you need to install ejs and express: npm install ejs express

    app.js file:

    var express = require('express');
    var app = express();
    
    app.set('view engine', 'ejs');
    
    app.get('/', function(req, res) {
      res.redirect('/home/2');
    });
    
    app.get('/home/:itemId', function(req, res) {
      var itemId = req.params.itemId;
      console.log(itemId);
      res.render('index');
    });
    
    app.get('/api/items/:itemId', function(req, res) {
      var itemId = req.params.itemId;
      console.log('item id: %s', itemId);
      res.json([{name: 'item1'}]);
    });
    
    app.listen(8080, function() {
      console.log('server up and running at 8080');
    });
    

    views/index.ejs file:

    <!doctype html>
    <html>
      <head>
      </head>
    
      <body>
            <h1>Hello World!</h1>
            <script>
    
                    function responseGET() {
                      if(this.readyState !== 4 || this.status !== 200) return;
                      alert(this.responseText);
                    }
    
                    function getItems(URL) {
                      var request = new XMLHttpRequest();
                      request.open('GET', URL, true);
                      request.onreadystatechange = responseGET.bind(request);
                      request.send(null);
                    }
    
                    function domReady() {
                      getItems('http://localhost:8080/api/items/1');
                    }
    
                    document.addEventListener('DOMContentLoaded', domReady);
            </script>
      </body>
    </html>
    

    Basically I am have a server which is serving an index.html when someone requests at /home/:itemId and also I am exposing another route for serving items /api/items/:itemId.

    From the client side once the DOM is ready I am requesting to /api/items/:itemId some items which then are displayed in the index html.

    评论

报告相同问题?

悬赏问题

  • ¥60 如何批量获取json的url
  • ¥15 对法兰连接元件所承受的表面载荷等效转化为法兰开孔接触面上的等效表面载荷?
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼