Json-server: Routes functionality doesn't work for static files

Created on 16 Jul 2017  路  2Comments  路  Source: typicode/json-server

Routes functionality doesn't work for static files. Here is the very simple demo setup:

// routes.js
{ "/t1.txt": "/t2.txt" }

// running server as
json-server db.json --static . --routes routes.js

And I get 404 for the request localhost:3000/t1.txt althought t2.txt is in the root folder.

The problem is that rewrite middleware is lower in the middleware stack than server static middleware, it can be seen here:

  if (argv.static) {
    defaultsOpts.static = path.join(process.cwd(), argv.static);
  }

  var defaults = jsonServer.defaults(defaultsOpts);
  app.use(defaults);

  if (routes) {
    var rewriter = jsonServer.rewriter(routes);
    app.use(rewriter);
  }

  if (middlewares) {
    app.use(middlewares);
  }

And the same problem is that functions from middlewares are also lower than serve static, which can be seen in this reported issue.

I think both routes and middlewares configurations defined by the consumer should be on top of the middleware stack. If simply move if (routes) {...} and if (middlewares) {...} blocks before the app.use(defaults); everything works fine.

I'm willing to make a pull request. Will it be accepted?

Most helpful comment

Would love to see this fixed - use case is we have an API /file/download/<fileName> and it'd be great to test that works in npm dev with a static file download. Ended up using a workaround for it in webpack inside the webpack.dev.config.js, in devServer:

      proxy: {
        '/file/': {
          target: 'http://localhost:3042/',
          pathRewrite: {
            '^/file/': '',
          }
        }
      }

The file sits in static/download with the below in the json config:

   "static": "json-server/static",

Not an ideal workaround but got it going. Hopefully helps someone else

All 2 comments

Would love to see this fixed - use case is we have an API /file/download/<fileName> and it'd be great to test that works in npm dev with a static file download. Ended up using a workaround for it in webpack inside the webpack.dev.config.js, in devServer:

      proxy: {
        '/file/': {
          target: 'http://localhost:3042/',
          pathRewrite: {
            '^/file/': '',
          }
        }
      }

The file sits in static/download with the below in the json config:

   "static": "json-server/static",

Not an ideal workaround but got it going. Hopefully helps someone else

I encountered this problem as well. Any progress on it?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sharpmachine picture sharpmachine  路  4Comments

melnikovic picture melnikovic  路  3Comments

bahmutov picture bahmutov  路  3Comments

shikaan picture shikaan  路  3Comments

casvil picture casvil  路  4Comments