Json-server: 404 on home page if public directory exists in the root of the project

Created on 10 Mar 2020  路  6Comments  路  Source: typicode/json-server

If there is public directory in the root of the project then json-server attempts to serve index.html from there, as result the home page is not working.

Steps for reproduction of the bug:

  1. install json-server into fresh npm project
  2. create public directory in the root of this new project
  3. create db.json
  4. start npx json-server db.json
  5. check http://localhost:3000/

Expected behavior: home page should work
Actual behavior: home page doesn't work (404 error)

Most helpful comment

My solution :

const fs = require('fs');
const path = require('path');
const server = require('json-server');
const routes = require('./routes');

const app = server.create();
const middlewares = server.defaults({
  static: path.join(__dirname, '../node_modules/json-server/public')
});

All 6 comments

One possible fix is to delete default static fallback into public directory and suggest users always use --static option for serving static files.

Here is part of the code that cause this issue:
https://github.com/typicode/json-server/blob/622400f7ead64f02e626a7eaa38035fd1438b835/src/server/defaults.js#L11-L15

@typicode hi! What do you think about removing default public fallback?

I figured the better solution is to separate creation of users static server from static server that is used for serving json-server related stuff.

My solution :

const fs = require('fs');
const path = require('path');
const server = require('json-server');
const routes = require('./routes');

const app = server.create();
const middlewares = server.defaults({
  static: path.join(__dirname, '../node_modules/json-server/public')
});

My solution :

const fs = require('fs');
const path = require('path');
const server = require('json-server');
const routes = require('./routes');

const app = server.create();
const middlewares = server.defaults({
  static: path.join(__dirname, '../node_modules/json-server/public')
});

Or in my case, I added the static route on the config file json-server.json;

{
    "port": 3000,
    "static": "'./node_modules/json-server/public'"
}

When I change the static ,

the page that json-server opens no longer shows' You're running JSON Server , but instead becomes a blank page .

Why is that ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jasonlimantoro picture jasonlimantoro  路  4Comments

TXRRNT picture TXRRNT  路  4Comments

fishenal picture fishenal  路  3Comments

sharpmachine picture sharpmachine  路  4Comments

bahmutov picture bahmutov  路  3Comments