typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
73.02k stars 7.02k forks source link

it doesn't work on xxx.js or remote url,though xxx.json is ok #1543

Open nillwyc opened 6 months ago

nillwyc commented 6 months ago

it doesn't work on xxx.js or remote url,though xxx.json is ok

does anyone have the same problem as mine?

my Node.js:v18.19.0

this is a .js file in my work folder.

module.exports = () => {
  const data = { users: [] };
  // Create 1000 users
  for (let i = 0; i < 1000; i++) {
    data.users.push({ id: i, name: `user${i}` });
  }
  return data;
};

i tested these codes which copied on https://github.com/typicode/json-server/tree/v0 but something wrong


(base) PS T:\router> json-server --version
1.0.0-alpha.23

(base) PS T:\router> json-server http://jsonplaceholder.typicode.com/db
File http://jsonplaceholder.typicode.com/db not found

(base) PS T:\router> json-server --watch db.js
--watch/-w can be omitted, JSON Server 1+ watches for file changes by default
undefined:1
module.exports = () => {
^

SyntaxError: Unexpected token m in JSON at position 0
    at JSONFile.parse (<anonymous>)
    at JSONFile.read (file:///T:/myDev/env/nvm1.1.10/v18.19.0/node_modules/json-server/node_modules/lowdb/lib/adapters/node/DataFile.js:17:31)
    at async Observer.read (file:///T:/myDev/env/nvm1.1.10/v18.19.0/node_modules/json-server/lib/observer.js:21:22)
    at async Low.read (file:///T:/myDev/env/nvm1.1.10/v18.19.0/node_modules/json-server/node_modules/lowdb/lib/core/Low.js:16:22)
    at async file:///T:/myDev/env/nvm1.1.10/v18.19.0/node_modules/json-server/lib/bin.js:114:1

Node.js v18.19.0
spanic commented 2 weeks ago

Well, .js files are not supported anymore as a source for database generation, as it comes from

https://github.com/typicode/json-server/blob/6aa56d9581488d9bcd1baf42c4c97b293cd9ee99/src/bin.ts#L128-L136

Obviously, json-server expects only .json5 and .json files, these changes have been made in PR https://github.com/typicode/json-server/pull/1468. However you can install latest >= 0.X.X version (0.17.4 as for today), where .js still can be used:

https://github.com/typicode/json-server/blob/baf0aee90ae62a7afed180f49ce91b946f218f0e/src/cli/utils/load.js#L48-L62

Looks like you also want to generate data - I also had the same task, and I solved it by creating.json file with Node.js script and then using this file as a source for json-server: https://gitverse.ru/austin_s/react-interview-task-v3/content/main/server/index.cjs