Giter Site home page Giter Site logo

json-server's Introduction

json-server

Node.js CI

Important

Viewing alpha v1 documentation – usable but expect breaking changes. For stable version, see here

Install

npm install json-server

Usage

Create a db.json or db.json5 file

{
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}
View db.json5 example
{
  posts: [
    { id: '1', title: 'a title', views: 100 },
    { id: '2', title: 'another title', views: 200 },
  ],
  comments: [
    { id: '1', text: 'a comment about post 1', postId: '1' },
    { id: '2', text: 'another comment about post 1', postId: '1' },
  ],
  profile: {
    name: 'typicode',
  },
}

You can read more about JSON5 format here.

Pass it to JSON Server CLI

$ npx json-server db.json

Get a REST API

$ curl http://localhost:3000/posts/1
{
  "id": "1",
  "title": "a title"
}

Run json-server --help for a list of options

Sponsors ✨

Sponsors

Become a sponsor and have your company logo here

Sponsorware

Note

This project uses the Fair Source License. Only organizations with 3+ users are kindly asked to contribute a small amount through sponsorship sponsor for usage. This license helps keep the project sustainable and healthy, benefiting everyone.

For more information, FAQs, and the rationale behind this, visit https://fair.io/.

Routes

Based on the example db.json, you'll get the following routes:

GET    /posts
GET    /posts/:id
POST   /posts
PUT    /posts/:id
PATCH  /posts/:id
DELETE /posts/:id

# Same for comments
GET   /profile
PUT   /profile
PATCH /profile

Params

Conditions

  • ==
  • lt<
  • lte<=
  • gt>
  • gte>=
  • ne!=
GET /posts?views_gt=9000

Range

  • start
  • end
  • limit
GET /posts?_start=10&_end=20
GET /posts?_start=10&_limit=10

Paginate

  • page
  • per_page (default = 10)
GET /posts?_page=1&_per_page=25

Sort

  • _sort=f1,f2
GET /posts?_sort=id,-views

Nested and array fields

  • x.y.z...
  • x.y.z[i]...
GET /foo?a.b=bar
GET /foo?x.y_lt=100
GET /foo?arr[0]=bar

Embed

GET /posts?_embed=comments
GET /comments?_embed=post

Delete

DELETE /posts/1
DELETE /posts/1?_dependent=comments

Serving static files

If you create a ./public directory, JSON Serve will serve its content in addition to the REST API.

You can also add custom directories using -s/--static option.

json-server -s ./static
json-server -s ./static -s ./node_modules

Notable differences with v0.17

  • id is always a string and will be generated for you if missing
  • use _per_page with _page instead of _limitfor pagination
  • use Chrome's Network tab > throtling to delay requests instead of --delay CLI option

json-server's People

Contributors

adamsea avatar bahmutov avatar barrystaes avatar blainsmith avatar blowsie avatar bva-financial-com avatar danielruf avatar dependabot[bot] avatar failpunk avatar gschutz avatar illandril avatar ilyasakin avatar jacobwardio avatar jameelmoses avatar jantrienes avatar jgautheron avatar jmzagorski avatar jsanford42 avatar kapekost avatar manavm1990 avatar manuquentin avatar nilegfx avatar patrickjs avatar ruifortes avatar siawyoung avatar sija avatar striezel avatar syzer avatar textbook avatar typicode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-server's Issues

Cannot find module 'low'

Out of the box, I got this error:

$ json-server issues.json

module.js:340
throw err;
^
Error: Cannot find module 'low'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/usr/local/lib/node_modules/json-server/src/cli.js:5:15)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)

server.run(db, [options]) -> Error: Object function has no method 'run'

Node v 0.10.24, json-server v 0.3.1

Invoking "json-server" as node module:
var server = require('json-server'),
db = require('./seed').run();
var options = { port: 4000, readOnly: true };
server.run(db, options);

returns error:
server.run(db, options);
^
TypeError: Object function app(req, res, next){ app.handle(req, res, next); } has no method 'run'
at Object. (/home/darek/testbox/json-server/index.js:6:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

wrong http status codes

such as returning "200 OK" instead "201 CREATED" after creating a new resource. (POST /resources)

[Feature Request] Allow for pre-configuring jsonServer.create() server

Hi! Thanks for JSON Server; it's awesome.

I've got a use case where I'm trying to run a json-server express instance, but I need to add some additional middleware before the static file handling gets added to the middleware stack. I began work toward enabling this, but was debating between a few varying solutions, so before I go any further I thought I'd ping you for your thoughts. Firstly, would you be on board with this enhancement? If so, I was thinking any of the following made sense:

  1. Update create to accept a callback. This callback would receive the express() server as an argument, which it could then use to do any configuration needed.
  2. Similar to #1, update create to accept an options object with a designated callback (e.g., options.preconfigure) to do the same configuration. This solution is arguably more future-proof.
  3. Update create to accept an optional express server instance, defaulting back to express() like it does currently. The downside to this is that it puts the onus of express dependency management on the user instead of in json-server.

Thoughts? I'd be happy to submit a PR for this.

Add delay

Add delay option to return requests. Just to be able to test in a more real way.

Writing an empty string stores a 0

Writing an empty string stores a 0

> curl -H "Content-Type: application/json" -X POST http://localhost:3000/posts -d'{"id":6,"comment":""}'
{"id":6,"comment":0}

> curl -H "Content-Type: application/json" -X GET  http://localhost:3000/posts/6
{"id":6,"comment":0}

Allow json server application to be mounted

I need to create a mocking server containing some REST routes, and some non-rest routes (command-like routes like POST /login).

I've tried to mount the json-server app, and went to the point where everything works, except json-server route calls are logged twice:

var express        = require('express');
var methodOverride = require('method-override')
var bodyParser     = require('body-parser')
var jsonServer     = require('json-server');
var cors           = require('cors');
var errorhandler   = require('errorhandler');
var logger         = require('morgan');

var port = process.env.PORT || 3000;

// create http server
var server = express()
server.set('port', port);
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(methodOverride());
server.use(cors({ origin: true, credentials: true }));
if (process.env.NODE_ENV === 'development') {
  // only use in development
  server.use(errorhandler());
}

// custom routes
server.post('/login', function(req, res) {
    res.json({name: "John Doe", access_token:"3A364F68DA5745EB653457A585678"});
});

// mount jsonServer
jsonServer.low.db = require('./seed').run();
server.use(jsonServer);

server.listen(port);
console.log('Mock server listening on port ' + port);
console.log('Press CTRL+C to stop server');

I think this is a fairly common use case, and IMO it should be more straightforward. Could you make the logging optional (i.e. if the json-server application is mounted, disable the logging)?

DELETE call deletes all the entries.

I am providing json file as a db source containing post elements as in : https://gist.github.com/injulkarnilesh/4cfd42501bfd5c13885f
Rest of the calls work fine
GET /posts/
GET /posts/3
POST /posts/
These calls work as expected.

But on
DELETE /posts/3
Response says
Response does not contain any data.
with status 204.
and json data in the file gets emptied to
{
"posts": []
}

Shouldn't it delete only the mentioned post rather than all the posts?

Json-server and lowdb

Hey again :)

I'm working on https://github.com/Shuunen/pracker

The aim of this tool is to watch a product price on the web and update a UI to alert the user when a product price changed.

So I use lowdb and json-server on the same file and you can see my implementation here : https://github.com/Shuunen/pracker/blob/master/pracker.js

On line 51 I added a "foo bar" test : product.toto = 42;

By db.json file is never updated with this.

But, if I comment the //Server init :

// Server
var jsonServer = require('json-server');
var router = jsonServer.router(dbFile);
var server = jsonServer.create();
server.use(jsonServer.defaults);
server.use(router);
server.listen(3000);

I will find my product.toto = 42 in db.json

So I think json-server is locking the file and prevent lowdb from updating, right ?

Ability to request sub-object

I was wondering if it's possible to do something like GET /member/user or GET /member/user/emails or something so that the REST routes are "subroutes".

Return 404s?

Any way to add a setting/feature that would return 404 status codes instead of [] for unmatched GET requests? I imagine that the 200 response is useful for most people, but it would aid rapid development with json-server if we knew that we mistyped something.

My specific use case is in leveraging the ./public static file serving feature and not getting warnings that we're looking for something that doesn't exist yet.

When require('json-server') in parent app, Express middleware doesn't get executed

Hi,

I assume I'm doing something wrong here…
Here is my app.js:

var server = require('json-server')
var app = server({ schemas: [] }, 'db.json')

app.use(function (req, res, next) {
    console.log('Time:', Date.now());
    next();
})

app.listen(process.env.PORT || 3000)

This doesn't print anything to the terminal…

Thanks for your time.

GET /:parent/:parentId/:resource when parentId doesn't exist deletes the :resource

Hi,

Thanks for this module, very, very helpful…
But now I'm pushing it further, I'm stumbling upon some problems.

For example, if you GET /posts/4/comments and the post with id 4 does not exist the entire comments resource will be deleted. This happens very inconsistently and I have not been able to debug it so far.

Do you have any idea of what could cause this?

Thanks for your time.

Possible to write to files?

When I saw in the readme that PUT and POST requests are supported, I expected that to mean the underlying JSON files can be written to via HTTP. Is that the case?

If not, wouldn't that be cool?!

Require error (chalk.grey)

When I'm lauching the server-json I get this error:

TypeError: Object #<Chalk> has no method 'grey'
    at start (/home/giacomo/lib/node_modules/json-server/bin/index.js:41:23)
    at Object.<anonymous> (/home/giacomo/lib/node_modules/json-server/bin/index.js:83:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

I'm missing something?
Thanks

save to file as changes are made instead of time interval

I am running the json-server using my own json file. I am able to POST and PUT, and when I do, the server save the changes to the file periodically. Is there any way to specify that the server should save the file whenever there is a change, instead of a time interval? I could not figure out what the time interval is. It seems to be inconsistent.

Thanks in advance,
Jamie

How can I get random data

I would like some random data.
I creat db.js:

module.exports = function() {
  data = {  };

  data.id = Math.floor( Math.random()*9+1 );
  return data;
};

but still return old data
What should I do ?

Saving db does not work

After giving the save command, the snapshot is reported as created however no matching file exists.

$ node index.js db.json

{^ ^} Yo!

Loading database from db.json

http://localhost:3000/referrers

Enter `s` at any time to create a snapshot of the db

s

Saved snapshot to db-1420467984100.json

^C

$ ls
db.json     index.js

Installation incomplete?

In the documentation it says that issuing "GET /" should return default index file or content of ./public/index.html (useful if you need to set a custom home page). However, even though I have installed json-server according to the provided instructions, I don't have a public folder in my web root.

By the way, can I put my .json file anywhere I want, or does it have to be in the web root? To which folder will http://localhost:3000 point?

I am using a Windows 8.1 VM for this project.

Defferred callback problem

Using the wonderful service at http://jsonplaceholder.typicode.com/

var client = new $.RestClient('http://jsonplaceholder.typicode.com/');
var myPost = client.posts.read(10);
client.add('posts');
client.posts.update(102, {title: 'The title!!'}); // <--- this should cause an error

myPost
.done(function (data){
console.log('I have data: ' + data.title);
console.log('I have data: ' + JSON.stringify(data));
})
.fail(function (err){
console.log('err: ' + err);
})

client.show();

Instead of the "fail" callback being triggered, I get this :

PUT http://jsonplaceholder.typicode.com/posts/102/ 500 (Internal Server Error) 

Any idea what I am doing wrong? Thanks

How to serve image files?

Sample image link http://localhost:3000/assets/images/coffee/large/coffee.gif not working with json-server, it's not possible to server static assets? (script files, css styles, images)
Or is there any way to plug sharp (image resizer node package) into json-server

grunt plugin

Have you ever thought about to create a grunt plugin for this nice tool?

Is it ok for you if i create one?

Possible to run with namespaces?

Given the following JSON:

{

  "speakers": [
    {
      "id": 1,
      "name": "Bugs Bunny"
    },
    {
      "id": 2,
      "name": "Wile E. Coyote"
    },
    {
      "id": 3,
      "name": "Yosemite Sam"
    }
  ]

}

Is it possible to run json-server such that it responds to /api/v1/speakers rather than /speakers?

SyntaxError: Unexpected token ´╗┐on server launch

Trying to run json-server in CMD on a Windows 8.1 VM:

C:\path\to\webroot>json-server mockAPI.json

{^ ^} Yo!

Loading database from mockAPI.json

http://localhost:3000/issues

Enter `s` at any time to create a snapshot of the db


undefined:1
´╗┐{
^
SyntaxError: Unexpected token ´╗┐
    at Object.parse (native)
    at Function.low.parse (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:80:15)
    at new Low (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:17:24)
    at low (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\node_modules\lowdb\src\index.js:61:10)
    at module.exports (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\src\create-routes.js:12:14)
    at module.exports (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\src\index.js:30:16)
    at start (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\bin\index.js:48:3)
    at Object.<anonymous> (C:\Users\peqe\AppData\Roaming\npm\node_modules\json-server\bin\index.js:60:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)

provide watch data file change option

When using json-server db.json, if db.json is changed, the server will still return old data. It can be better if it is able to watch file change and refresh server data automatically.

full text search not working

after git clone and npm install and node ./bin/index.js, the full text search is not working.

db.json using:

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ]
}

Query using:

GET http://localhost:3000/post?q=json-server

It appears that the below code didn't run into the array = db().filter() and for loop is not running at all:

if (req.query.q) {

      // Full-text search
      var q = req.query.q.toLowerCase()
      array = db(req.params.resource).filter(function(obj) {
        for (var key in obj) {
          var value = obj[key]
          if (_.isString(value) && value.toLowerCase().indexOf(q) !== -1) {
            return true
          }
        }
      })

    } else {

Can anyone tell me how to get full text search working?

POST & PUT data to db

Hi,

If I get the readme well, it's possible to use POST and PUT to alter content of the db.json ?

Here is my db & server:

// Database
var low = require('lowdb');
low.mixin(require('underscore-db'));
var db = low('db.json');

// Server
var jsonServer = require('json-server');
var router = jsonServer.router(db.object); // Express router
var server = jsonServer.create();          // Express server
server.use(jsonServer.defaults);           // Default middleware (logger, public, ...)
server.use(router);
server.listen(3000);

my data in db.json :

"posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],

and the request I sent with jQuery on client side :

$.ajax({
  method: "POST",
  url: "/posts",
  data: {"id": 2, "title": "title test"}
});

here is my request visible in chrome dev tools :

General :
Remote Address:127.0.0.1:3000
Request URL:http://127.0.0.1:3000/posts
Request Method:POST
Status Code:200 OK

Response Headers :
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://127.0.0.1:3000
Connection:keep-alive
Content-Length:38
Content-Type:application/json; charset=utf-8
Date:Sun, 26 Apr 2015 21:11:59 GMT
ETag:W/"26-224df703"
Vary:Origin, X-HTTP-Method-Override
X-Content-Type-Options:nosniff
X-Powered-By:Express

Request header :
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:fr,en-GB;q=0.8,en;q=0.6
Connection:keep-alive
Content-Length:21
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
DNT:1
Host:127.0.0.1:3000
Origin:http://127.0.0.1:3000
Referer:http://127.0.0.1:3000/?
User-Agent:Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
X-Requested-With:XMLHttpRequest

Form Data :
id:2
title:title test

and the response :

{
  "id": 2,
  "title": "title test"
}

The problem is : db.json is not updated.

It's weird because when I get to http://127.0.0.1:3000/posts I can see the added post :

[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode"
  },
  {
    "id": 2,
    "title": "title test"
  }
]

Any idea ?

Thanks :)

PUT requests: Boolean values(true, false) getting converted to 1, 0

The boolean values, in a PUT request data load, gets stored as 0 or 1 (for false and true respectively). On research, I found in routes.js, there is a call to toNative method from utils module. The toNative method converts boolean literal values to integer numbers like 0 or 1.

I think the toNative method should convert only the string values to its native equivalent.

Please advise.

Numeric values stored as strings

When I post a json with numeric values in it, e.g.

$.post("http://localhost:3000/test", {x:1,y:2}, 'json');

json-server stores the values as strings:

{"x":"1","y":"2"}

,which is a problem for me because the filter won't work with string values:

http://localhost:3000/test?x=1

I did a quick and dirty fix by adding:

for (var key in req.body)
    req.body[key] = utils.toNative(req.body[key]);

...at the start of routes.create and routes.update

whole collection deleted if one of the fieldnames ends with Id

Hi,
given a database like

"keywords": [
    {
        "id": 0,
        "entity": "messages",
        "entityId": 5,
        "value": "mollit"
    },
    {
        "id": 1,
        "entity": "messages",
        "entityId": 1,
        "value": "consequat"
    }
]

if I delete an item with DELETE /keywords/1, then all keywords are deleted. If I rename entityId to entityRef, everything is fine.

Is there any way I can specify that entityId is not a foreign key ?

Thanks,
Alain

ids as string codes

This (awesome) projects don't let you use integer ids.

In other words, you can provide something like:

{
  "posts": [
    { "id": "1", "body": "foo" },
    { "id": "2", "body": "bar" }
  ],
  "comments": [
    { "id": "1", "body": "baz", "postId": "1" },
    { "id": "2", "body": "qux", "postId": "2" }
  ]
}

If you visit /posts it works, but if you try to get /posts/1 you get no results.
Sometimes it is useful having string identifiers or when you have to simulate an existing environment.

Does it make sense for you? Is there a workaround for this?

Nested requests returning 404

So I have a json file that has the following schema:

{
  "environments": [
    {
      "id": 12,
      "reports": [
        {
          "id": 17
        },
        {
          "id": 25
        }
      ]
    },
    {
      "id": 19,
      "reports": [
        {
          "id": 22
        },
        {
          "id": 30
        }
      ]
    }
  ]
}

/environments works, as does /environments/12, so I figured I could use the route /environments/12/reports to return that array, but it's returning a 404 instead. Am I doing something wrong here?

My env:

  • Mac OS X Yosemite
  • NVM 0.24.0
  • io.js 1.8.1
  • json-server 0.7.3

Error HTTP 413 Request entity too large

The body-parser has an (Object) options parameter that accept a limit - maximum request body size. (default: <100kb>), my application have too many data, I have to set this value to 10mb so I will fork and commit my changes.

That's the error HTTP 413:

Error: request entity too large
    at makeError (/usr/lib/node_modules/json-server/node_modules/body-parser/node_modules/raw-body/index.js:184:15)
    at module.exports (/usr/lib/node_modules/json-server/node_modules/body-parser/node_modules/raw-body/index.js:40:15)
    at read (/usr/lib/node_modules/json-server/node_modules/body-parser/lib/read.js:62:3)
    at urlencodedParser (/usr/lib/node_modules/json-server/node_modules/body-parser/lib/types/urlencoded.js:84:5)
    at Layer.handle [as handle_request] (/usr/lib/node_modules/json-server/node_modules/express/lib/router/layer.js:82:5)
    at trim_prefix (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:271:13)
    at /usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:238:9
    at Function.proto.process_params (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:313:12)
    at /usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:229:12
    at Function.match_layer (/usr/lib/node_modules/json-server/node_modules/express/lib/router/index.js:

PATCH method?

PATCH method not exposed in response CORS headers:

curl -X OPTIONS -v -H "Access-Control-Request-Method: PATCH" http://localhost:3000/

* About to connect() to localhost port 3000 (#0)
*   Trying 127.0.0.1... connected
> OPTIONS / HTTP/1.1
> User-Agent: curl/7.23.1 (x86_64-pc-win32) libcurl/7.23.1 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:3000
> Accept: */*
> Access-Control-Request-Method: PATCH
>
< HTTP/1.1 204 No Content
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE
< Date: Thu, 01 May 2014 04:07:22 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
* Closing connection #0

object is not a function

I installed json-server globally and I followed the instruction to make a test json file:
{ "people": [ { "fname": "Bashar", "lname": "Ayyash" } ] }

When I started json-server I received the following error:
C:\Program Files\nodejs\node_modules\json-server\bin\index.js:54
server(object, filename).listen(port)
^
TypeError: object is not a function
at start (C:\Program Files\nodejs\node_modules\json-server\bin\index.js:54:3)
at Object. (C:\Program Files\nodejs\node_modules\json-server\bin\index.js:68:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3

Why is this?

Please advice,

Authentication

This is awesome. Thanks for your work here! Wondering how you/if you would go about setting up some sort of fake authentication system. Specifically, I want to use JWT. Do you think there's room for something like this in this project?

About X-Total-Count

May we provide information in X-Total-Count like JSON parameter?
In my case: I use ExtJS for build my application. Currently I have problem with getting information from response header.
In my opinion: We can make json-server response like
{ count: .... , data: .... }

Multiple files

Would be very useful to serve directory, rather than 1 file. Say you got accounts.json, and flight.json, would be great to call something json server src/app/db/. and ability to call localhost:3000/accounts for accounts file

Cannot create items when json-server is mounted on an existing Express Server

Hello! I've mounted json-server on an existing Express Server in this way:

var express = require('express');
var jsonServer = require('json-server');

var app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'jade');

// Route index
app.get('/', function (req, res) {
    res.render('index');
});

var router = jsonServer.router(require('./api.js')());

app.use(router);

app.listen(3000, function() {
    console.log('Static server and APIs listening on port 3000');
});

Now when I call a POST route on this server I receive this error:

TypeError: Cannot read property 'id' of undefined
    at Function.module.exports.insert (D:\projects\api\node_modules\json-server\node_modules\underscore-db\src\index.js:45:12)

While if I start json-server stand alone json-server api.js everything works as expected and I receive the newly created items as reponse.

I've made some mistakes with my Express server? Is there a better way to integrate json-server with Express? Thank you.

Allow the use of nested resource key

Hello and thanks for your great work!

I have a little problem. We use a structure like this:

{
  "data": [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Jake"
    },
  ],
  "meta": {
    "total": 2,
    "page": 1
  }
}

Now I can write the structure in my generate.js with the "data" and "meta" keys and it return correctly when I call /user.

Anyway when I try to get a single element of the collection, say /user/1, it returns me an empty object with a 404 http code.

I understand that this is a non-conventional request, but do you think that a situation like that could be handled via some config file or options passed to the CLI?

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.