Question

I'm using Node.js for the first time. I'm serving up static files with node-static and routing with journey. Unfortunately the two seem to conflict with each other, and I'm not sure of the best way to stop the conflict. My server looks like this:

var http = require('http');
var nodeStatic = require('node-static');
var journey = require('journey');

var fileServer = new nodeStatic.Server('./public');
var router = new journey.Router;


module.exports = http.createServer(function (req, res) {
  router.get('/api').bind(function (req, res) {
    res.send(200);
  });
var fileServer = new nodeStatic.Server('./public');
var router = new journey.Router;


module.exports = http.createServer(function (req, res) {
  router.get('/api').bind(function (req, res) {
    res.send(200);
  });

  req.addListener('end', function () {
    fileServer.serve(req, res);

    router.handle(req, '', function (result) {
      res.writeHead(result.status, result.headers);
      res.end(result.body);
    });
  });
});

The problem with this is that the Journey router sends a 404 response. The only way I've managed to make it work is by doing this in the end listener:

  req.addListener('end', function () {
    router.handle(req, '', function (result) {
      if (result.status === 404) {
        fileServer.serve(req, res);
      }
      else {
        res.writeHead(result.status, result.headers);
        res.end(result.body);
      }
    });
  });

but this doesn't seem like the way I should be handling things. What am I doing wrong?

Was it helpful?

Solution

I found a gist showing how to use node-static with journey. I basically had it right. I'd be happy to hear any alternative solutions though!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top