简体   繁体   English

Express.js res.render和res.json

[英]Express.js res.render and res.json

i have some problem with express.js. 我对express.js有一些问题。 I want to render my template on first request, and then get some data from routs. 我想在第一次请求时渲染我的模板,然后从溃败中获取一些数据。 My routing look like: 我的路由如下所示:

app.use(function (req, res, next) {
 res.render('index.jade');
 next();
});

app.get('/', function(req, res){  
  res.json({a:1});
})

app.get('/contacts', function(req, res){  
  res.json({a:1});
})

app.get('/emails', function(req, res){  
  res.json({a:1});
})

The problem is that every request i do, set response to html/text by my middleware, and i can't get to other routs. 问题是我执行的每个请求都将响应设置为中间件对html / text的响应,而我无法达到其他要求。 Mb some one know how i can render template only once, and than be able to get to the other routs (i try to do SPA with express and backbone) mb有人知道我只能渲染模板一次,而不是去其他路由(我尝试使用Express和骨干网进行SPA)

Solutions You convert jade to html and place index.html file in the public folder 解决方案:将jade转换为html并将index.html文件放置在公用文件夹中

Enable express static files serve 启用快速静态文件投放

app.use(express.static('public'));

define and other specific routes returns static files and api like in (api|css|js) define和其他特定路由返回静态文件和api,如(api | css | js)

    app.route('/:url(api|css|js)/*')
       .get(function (req, res) {
          var viewFilePath = '404';
          var statusCode = 404;
          var result = {
            status: statusCode
          };

          res.status(result.status);
          res.render(viewFilePath, function (err) {
            if (err) { return res.json(result, result.status); }
    // 404.jade file
            res.render(viewFilePath);
          });
        });

      // All other routes should redirect to the index.html
      app.route('/*')
        .get(function(req, res) {
// SPA index  file
          res.sendfile('/public/index.html');
        });

Now you can use 现在您可以使用

app.get('/api/emails', function(req, res){  
  res.json({a:1});
});
app.get('/api/contacts', function(req, res){  
  res.json({a:1});
});

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

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