Serhiy Ryazanov
Serhiy Ryazanov

Reputation: 61

Express.js res.render and res.json

i have some problem with 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. 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)

Upvotes: 0

Views: 7956

Answers (1)

Manjesh V
Manjesh V

Reputation: 1240

Solutions You convert jade to html and place index.html file in the public folder

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)

    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});
});

Upvotes: 2

Related Questions