json-server | Get a full fake REST API with zero coding in less than 30 seconds (seriously) | REST library

 by   typicode JavaScript Version: 0.17.3 License: MIT

kandi X-RAY | json-server Summary

json-server is a JavaScript library typically used in Web Services, REST, Nodejs applications. json-server has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i xl-json-server' or download it from GitHub, npm.
Get a full fake REST API with zero coding in less than 30 seconds (seriously). Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        json-server has a medium active ecosystem.
                        summary
                        It has 66184 star(s) with 6523 fork(s). There are 1012 watchers for this library.
                        summary
                        There were 3 major release(s) in the last 6 months.
                        summary
                        There are 568 open issues and 471 have been closed. On average issues are closed in 309 days. There are 86 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of json-server is 0.17.3
                        json-server Support
                          Best in #REST
                            Average in #REST
                            json-server Support
                              Best in #REST
                                Average in #REST

                                  kandi-Quality Quality

                                    summary
                                    json-server has 0 bugs and 0 code smells.
                                    json-server Quality
                                      Best in #REST
                                        Average in #REST
                                        json-server Quality
                                          Best in #REST
                                            Average in #REST

                                              kandi-Security Security

                                                summary
                                                json-server has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                json-server code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                json-server Security
                                                  Best in #REST
                                                    Average in #REST
                                                    json-server Security
                                                      Best in #REST
                                                        Average in #REST

                                                          kandi-License License

                                                            summary
                                                            json-server is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            json-server License
                                                              Best in #REST
                                                                Average in #REST
                                                                json-server License
                                                                  Best in #REST
                                                                    Average in #REST

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        json-server releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in npm.
                                                                        summary
                                                                        Installation instructions, examples and code snippets are available.
                                                                        summary
                                                                        json-server saves you 66 person hours of effort in developing the same functionality from scratch.
                                                                        summary
                                                                        It has 172 lines of code, 0 functions and 36 files.
                                                                        summary
                                                                        It has low code complexity. Code complexity directly impacts maintainability of the code.
                                                                        json-server Reuse
                                                                          Best in #REST
                                                                            Average in #REST
                                                                            json-server Reuse
                                                                              Best in #REST
                                                                                Average in #REST
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed json-server and discovered the below as its top functions. This is intended to give you an instant insight into json-server implemented functionality, and help decide if they suit your requirements.
                                                                                  • list resource names
                                                                                    • Start the server
                                                                                      • Creates a new app .
                                                                                        • Update a resource .
                                                                                          • Get a list of references from the collection .
                                                                                            • get page object
                                                                                              • Display a resource
                                                                                                • Prints the list of resources
                                                                                                  • Remove document related to the database
                                                                                                    • Block to produce custom routes
                                                                                                      Get all kandi verified functions for this library.
                                                                                                      Get all kandi verified functions for this library.

                                                                                                      json-server Key Features

                                                                                                      Egghead.io free video tutorial - Creating demo APIs with json-server
                                                                                                      JSONPlaceholder - Live running version
                                                                                                      My JSON Server - no installation required, use your own data
                                                                                                      :dog: husky - Git hooks made easy
                                                                                                      :owl: lowdb - local JSON database
                                                                                                      ✅ xv - a beautifully simple and capable test runner

                                                                                                      json-server Examples and Code Snippets

                                                                                                      json-server is not recognized as an internal or external command
                                                                                                      JavaScriptdot imgLines of Code : 4dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      npm install -g json-server
                                                                                                      
                                                                                                      npx json-server --watch db.json
                                                                                                      
                                                                                                      "json-server" command not found in Docker container even though it is installed
                                                                                                      JavaScriptdot imgLines of Code : 16dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      FROM node:10-alpine as build-step    
                                                                                                      RUN mkdir -p /app    
                                                                                                      WORKDIR /app    
                                                                                                      COPY package.json /app   
                                                                                                      RUN npm install    
                                                                                                      COPY . /app    
                                                                                                      RUN npm run build --prod 
                                                                                                       
                                                                                                      # Stage 2
                                                                                                      FROM nginx:1.17.1-alpine
                                                                                                      COPY nginx.conf /etc/nginx/nginx.conf
                                                                                                      COPY --from=build-step /app/dist/my-app /usr/share/nginx/html
                                                                                                      RUN npm install json-server 
                                                                                                      
                                                                                                      CMD json-server --watch services/mock-api/db.json --routes services/mock-api/routes.json --port 3000 --host 0.0.0.0
                                                                                                      
                                                                                                      Prefix all requests in JSON Server with middleware
                                                                                                      JavaScriptdot imgLines of Code : 24dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      // api-routes.js
                                                                                                      const express = require('express')
                                                                                                      const jsonServer = require('json-server')
                                                                                                      
                                                                                                      const router = express.Router()
                                                                                                      const server = jsonServer.create()
                                                                                                      const middlewares = jsonServer.defaults()
                                                                                                      const v1Router = jsonServer.router('db-v1.json')
                                                                                                      const v2Router = jsonServer.router('db-v2.json')
                                                                                                      
                                                                                                      
                                                                                                      router.use('/v1', v1Router)
                                                                                                      router.use('/v2', v2Router)
                                                                                                      
                                                                                                      module.exports = router
                                                                                                      
                                                                                                      const express = require('express')
                                                                                                      const apiRoutes = require('./api-routes')
                                                                                                      
                                                                                                      const app = express()
                                                                                                      app.use('/api', apiRoutes)
                                                                                                      
                                                                                                      // ...
                                                                                                      
                                                                                                      "json-server" command not found in Docker container even though it is installed
                                                                                                      JavaScriptdot imgLines of Code : 26dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      # Stage 1
                                                                                                      FROM node:10-alpine as build-step
                                                                                                      RUN mkdir -p /app
                                                                                                      WORKDIR /app
                                                                                                      COPY package.json /app
                                                                                                      RUN npm install
                                                                                                      COPY . /app
                                                                                                      RUN npm run build --prod
                                                                                                      
                                                                                                      # Stage 2
                                                                                                      FROM ubuntu:16.04
                                                                                                      USER root
                                                                                                      WORKDIR /home/app
                                                                                                      COPY package.json /home/app/package.json
                                                                                                      RUN apt-get update
                                                                                                      RUN apt-get -y install curl gnupg
                                                                                                      RUN curl -sL https://deb.nodesource.com/setup_11.x  | bash -
                                                                                                      RUN apt-get -y install nodejs
                                                                                                      RUN apt update
                                                                                                      RUN apt-get -y install nginx
                                                                                                      RUN npm i -g json-server
                                                                                                      
                                                                                                      COPY nginx.conf /etc/nginx/nginx.conf
                                                                                                      COPY --from=build-step /app/dist/my-app/usr/share/nginx/html
                                                                                                      CMD json-server --watch /usr/share/nginx/html/assets/mock-api/db.json --routes /usr/share/nginx/html/assets/mock-api/routes.json --no-cors --host 0.0.0.0
                                                                                                      
                                                                                                      My JSON Server from Typicode updating database in ReactJS
                                                                                                      JavaScriptdot imgLines of Code : 12dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      npm install -g json-server
                                                                                                      
                                                                                                      {
                                                                                                        "posts": [
                                                                                                          { "id": 1, "title": "json-server", "author": "typicode" }
                                                                                                        ]
                                                                                                      }
                                                                                                      
                                                                                                      json-server db.json
                                                                                                      
                                                                                                      json-server db.json -p 3001
                                                                                                      
                                                                                                      Cannot start docker image - "cannot find module json-server"
                                                                                                      JavaScriptdot imgLines of Code : 35dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      FROM node:lts-slim
                                                                                                      
                                                                                                      RUN npm install -g json-server
                                                                                                      
                                                                                                      WORKDIR /data
                                                                                                      VOLUME /data
                                                                                                      
                                                                                                      EXPOSE 3000
                                                                                                      ADD entrypoint.sh /entrypoint.sh
                                                                                                      ENTRYPOINT ["bash", "/entrypoint.sh"]
                                                                                                      CMD []
                                                                                                      
                                                                                                      #!/bin/bash
                                                                                                      
                                                                                                      args="$@"
                                                                                                      
                                                                                                      args="$@ --host 0.0.0.0 --port 3000"
                                                                                                      
                                                                                                      file=/data/db.json
                                                                                                      if [ -f $file ]; then
                                                                                                          echo "Found $file"
                                                                                                          args="$args --watch $file"
                                                                                                      fi
                                                                                                      
                                                                                                      echo "json-server $args"
                                                                                                      
                                                                                                      json-server $args
                                                                                                      
                                                                                                      json-server:
                                                                                                         build: ./json-server
                                                                                                         volumes:
                                                                                                           - ./json-server/json/:/data
                                                                                                         ports:
                                                                                                           - 3000:3000
                                                                                                      
                                                                                                      Host Provider Heroku doesn't seem to pick up concurrently command in "npm run start"
                                                                                                      JavaScriptdot imgLines of Code : 18dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      var express = require('express');
                                                                                                      var jsonServer = require('json-server');
                                                                                                      
                                                                                                      var app = express();
                                                                                                      
                                                                                                      //publish the static result of npm run build (vue)
                                                                                                      //https://github.com/jrichardsz/nodejs-express-snippets/tree/master/simple-static-server
                                                                                                      app.use('/',
                                                                                                        express.static(path.join(__dirname, "site" || proces.env.SITE_FOLDER)),
                                                                                                      );
                                                                                                      
                                                                                                      //run json-server programmatically here
                                                                                                      //https://github.com/typicode/json-server/issues/253#issuecomment-205509836
                                                                                                      app.use('/api', jsonServer.router('db.json'));
                                                                                                      
                                                                                                      app.listen(3000);
                                                                                                      
                                                                                                      
                                                                                                      Communicating between two docker services in docker-compose
                                                                                                      JavaScriptdot imgLines of Code : 29dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      version: '3'
                                                                                                      services:
                                                                                                        json-server:
                                                                                                          image: json-server-image:latest
                                                                                                          ports:
                                                                                                            - "3000:3000"
                                                                                                          container_name: json-server
                                                                                                          hostname: json-server
                                                                                                          networks:
                                                                                                            - some-net
                                                                                                        angular:
                                                                                                          image: angular-image:latest
                                                                                                          ports:
                                                                                                            - "8888:80"
                                                                                                          container_name: angular
                                                                                                          networks:
                                                                                                            - some-net
                                                                                                      
                                                                                                      networks:
                                                                                                        some-net:
                                                                                                          driver: bridge
                                                                                                      
                                                                                                      networks:
                                                                                                        some-net:
                                                                                                          driver: bridge
                                                                                                      
                                                                                                      networks:
                                                                                                            - some-net
                                                                                                      
                                                                                                      Update a json file from Angular
                                                                                                      JavaScriptdot imgLines of Code : 37dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      npm i -D @angular-builders/custom-webpack json-server
                                                                                                      ng config projects..architect.build.builder @angular-builders/custom-webpack:browser
                                                                                                      ng config projects..architect.build.options.customWebpackConfig.path custom-webpack.config.js
                                                                                                      ng config projects..architect.serve.builder @angular-builders/custom-webpack:dev-server
                                                                                                      ng config projects..architect.serve.options.customWebpackConfig.path custom-webpack.config.js
                                                                                                      
                                                                                                      const json = require('json-server');
                                                                                                      
                                                                                                      module.exports = {
                                                                                                        devServer: {
                                                                                                          before: function(app) {
                                                                                                            app.use('/api', json.router('db.json'));
                                                                                                          }
                                                                                                        }
                                                                                                      };
                                                                                                      
                                                                                                      {
                                                                                                          "users": []
                                                                                                      }
                                                                                                      
                                                                                                      const API = '/api/users/';
                                                                                                      
                                                                                                      @Injectable({
                                                                                                        providedIn: 'root'
                                                                                                      })
                                                                                                      export class AppService {
                                                                                                        constructor(private http: HttpClient) {}
                                                                                                      
                                                                                                        get(id: number) {
                                                                                                          return this.http.get(API + id);
                                                                                                        }
                                                                                                      
                                                                                                        post(user: any) {
                                                                                                          return this.http.post(API, user);
                                                                                                        }
                                                                                                      }
                                                                                                      
                                                                                                      How can I log my output to .txt file instead of the terminal in Expo?
                                                                                                      JavaScriptdot imgLines of Code : 16dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                                      copy iconCopy
                                                                                                      npm install -g json-server
                                                                                                      
                                                                                                      echo '{"logs": []}'> logs.json
                                                                                                      
                                                                                                      json-server logs.json
                                                                                                      
                                                                                                      let veryLargeTextWorks = "1234567890";
                                                                                                          for (let i = 0; i < 11; i++) {
                                                                                                            veryLargeTextWorks += veryLargeTextWorks;
                                                                                                          }
                                                                                                      // veryLargeTextWorks.length == 20480
                                                                                                      axios.post("http://localhost:3000/logs", {
                                                                                                            date: new Date(),
                                                                                                            msg: veryLargeTextWorks
                                                                                                          });
                                                                                                      
                                                                                                      Community Discussions

                                                                                                      Trending Discussions on json-server

                                                                                                      my state keeps adding empty elements into its array
                                                                                                      chevron right
                                                                                                      trying to make "npm run dev" create 2 shell instances
                                                                                                      chevron right
                                                                                                      json-server running but can't access its api due to 403
                                                                                                      chevron right
                                                                                                      I trying to json-server by npm install -g json-server, but everytime I get an error
                                                                                                      chevron right
                                                                                                      json-server returns HTTP 200 instead of 404 for query parameter filtered GET request, what is the best practice here & how can 404 be returned?
                                                                                                      chevron right
                                                                                                      How to use json-server | Getting 404 for local db.json
                                                                                                      chevron right
                                                                                                      Can't install json-server
                                                                                                      chevron right
                                                                                                      Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app
                                                                                                      chevron right
                                                                                                      In ' "db": "json-server -w db.json -p 3001" ', what is '-w' in here means?
                                                                                                      chevron right
                                                                                                      Is there a way to run server with a session-persisted database connection in Django?
                                                                                                      chevron right

                                                                                                      QUESTION

                                                                                                      my state keeps adding empty elements into its array
                                                                                                      Asked 2022-Apr-18 at 01:06

                                                                                                      My setter, for SetPersons, seems to keep adding empty elements into its array for no apparent reason. I am trying to make my phone number list update instantaneously when I update a user's number but it sticks with the old number. Whenever I apply the logic to possibly make the number update instantly, it adds empty elements into my array instead and does not update instantly. Here is the code for each separate component:

                                                                                                      App.js

                                                                                                      import { useEffect, useState, useRef} from 'react'
                                                                                                      import PersonForm from './components/PersonForm'
                                                                                                      import Display from './components/Display'
                                                                                                      import Filter from './components/Filter'
                                                                                                      import phoneService from './services/information'
                                                                                                      
                                                                                                      const App = () => {
                                                                                                        const [errorMessage, setErrorMessage] = useState('')
                                                                                                        const [persons, setPersons] = useState('')
                                                                                                        const [newName, setNewName] = useState('')
                                                                                                        const [newNumber, setNewNumber] = useState('')
                                                                                                        const [filter, setFilter] = useState('')
                                                                                                        const [filterChecker, setFilterChecker] = useState('')
                                                                                                        
                                                                                                        useEffect(() => {
                                                                                                          phoneService.getAll()
                                                                                                          .then(people => setPersons(people))
                                                                                                        }, [])
                                                                                                      
                                                                                                        const handleSubmit = (e) => {
                                                                                                          e.preventDefault();
                                                                                                          const copy = [...persons]
                                                                                                          const foundNameOrNot = persons.some(el => el.name === newName)
                                                                                                          const foundNumberOrNot = persons.some(el => el.number === newNumber)
                                                                                                          const eachPersonsID = persons.map(person => person.id)
                                                                                                          const newObj = {
                                                                                                            name: newName,
                                                                                                            number: newNumber,
                                                                                                            id: Math.max(eachPersonsID) + 1
                                                                                                          }
                                                                                                          if (foundNameOrNot) {
                                                                                                            if(window.confirm(`${newName} is added to phonebook, replace the old number with a new one.`)) {
                                                                                                              const indexFinder = persons.filter(person => person.name === newName)
                                                                                                              newObj.id = indexFinder[0].id
                                                                                                              copy[indexFinder[0].id] = newObj
                                                                                                              phoneService.update(indexFinder[0].id, newObj)
                                                                                                              .then(res => {
                                                                                                                setErrorMessage(`Successfully updated ${newName}s number`)
                                                                                                                setPersons([copy])})
                                                                                                              .catch(err => {
                                                                                                                setErrorMessage(`Information on ${newName} has already been removed`)
                                                                                                                setFilterChecker(filterChecker.filter(filter => filter !== newName))})
                                                                                                            }
                                                                                                          } else if (foundNumberOrNot) {
                                                                                                            alert(`${newNumber} belongs to someone else`)
                                                                                                          } else {
                                                                                                            phoneService.create(newObj).then(res => setPersons([...persons, newObj]))
                                                                                                          }
                                                                                                        }
                                                                                                      
                                                                                                        const handleFilter = (e) => {
                                                                                                          console.log(persons)
                                                                                                          setFilter(e.target.value)
                                                                                                          const allNames = persons.map(person => person.name)
                                                                                                          setFilterChecker(allNames.filter(name => name.toLowerCase().indexOf(filter.toLowerCase()) !== -1))
                                                                                                        }
                                                                                                      
                                                                                                        return (
                                                                                                          
                                                                                                            {errorMessage ? errorMessage : ''}
                                                                                                            Phonebook
                                                                                                            
                                                                                                            add a new
                                                                                                            
                                                                                                              
                                                                                                              
                                                                                                                add
                                                                                                              
                                                                                                            
                                                                                                            Numbers
                                                                                                            
                                                                                                          
                                                                                                        )
                                                                                                      }
                                                                                                      
                                                                                                      export default App
                                                                                                      

                                                                                                      Display.js

                                                                                                      import phoneService from '../services/information'
                                                                                                      import axios from 'axios'
                                                                                                      import { useState } from 'react'
                                                                                                      
                                                                                                      const handleDelete = (i, persons, setPersons, name2, setFilterChecker, errorMessage, setErrorMessage) => {
                                                                                                          if (window.confirm(`delete ${name2} ?`)) {
                                                                                                              const newArrayOfPeople = persons.filter(person => person.name !== name2)
                                                                                                              const newArrayOfNames = newArrayOfPeople.map(person => person.name)
                                                                                                              setFilterChecker(newArrayOfNames)
                                                                                                              setPersons(newArrayOfPeople)
                                                                                                              phoneService.remove(persons[i].id)
                                                                                                              setErrorMessage(`You have successfully deleted ${name2} from the list.`)
                                                                                                              setTimeout(() => {
                                                                                                                  setErrorMessage(null)
                                                                                                              }, 5000)
                                                                                                          }
                                                                                                      }
                                                                                                      
                                                                                                      const Display = ({filterChecker, persons, setPersons, setFilterChecker, errorMessage, setErrorMessage}) => {
                                                                                                          const copy = [...persons]
                                                                                                          const findNumbers = []
                                                                                                          const findNames = []
                                                                                                          for (let j = 0; j < copy.length; j++) {
                                                                                                              if (copy[j]?.name && !findNames.includes(copy[j]?.name)) {
                                                                                                                  findNames.push(copy[j].name)
                                                                                                              }
                                                                                                          }
                                                                                                          for (let i = 0; i < copy.length; i++) {
                                                                                                              if (copy[i]?.number && !findNumbers.includes(copy[i]?.number)) {
                                                                                                                  findNumbers.push(copy[i]?.number)
                                                                                                              }
                                                                                                          }
                                                                                                        if (filterChecker) {
                                                                                                          return (
                                                                                                            findNames.map((name, i) => {name} {findNumbers[i]}  handleDelete(i, persons, setPersons, name, setFilterChecker, errorMessage, setErrorMessage)}>delete)
                                                                                                            )
                                                                                                        } else {
                                                                                                          return ''
                                                                                                        }
                                                                                                      
                                                                                                      }
                                                                                                      
                                                                                                      export default Display
                                                                                                      

                                                                                                      Filter.js

                                                                                                      const Filter = ({filter, handleFilter}) => {
                                                                                                          return 

                                                                                                      filter shown with

                                                                                                      } export default Filter

                                                                                                      PersonForm.js

                                                                                                      import axios from 'axios';
                                                                                                      import phoneService from '../services/information'
                                                                                                      
                                                                                                      const PersonForm = ({newName, newNumber, setNewName, setNewNumber}) => {
                                                                                                      
                                                                                                        return (
                                                                                                          
                                                                                                            name:  setNewName(e.target.value)}/>
                                                                                                            number:  setNewNumber(e.target.value)}/>
                                                                                                          
                                                                                                        )
                                                                                                      }
                                                                                                      
                                                                                                      export default PersonForm
                                                                                                      

                                                                                                      information.js

                                                                                                      import axios from "axios"
                                                                                                      const baseUrl = 'http://localhost:3002/numbers'
                                                                                                      
                                                                                                      const getAll = () => {
                                                                                                        const request = axios.get(baseUrl)
                                                                                                      
                                                                                                        return request.then(response => response.data)
                                                                                                      }
                                                                                                      
                                                                                                      const create = newObject => {
                                                                                                        const request = axios.post(baseUrl, newObject)
                                                                                                        return request.then(response => response.data)
                                                                                                      }
                                                                                                      
                                                                                                      const update = (id, newObject) => {
                                                                                                        const request = axios.put(`${baseUrl}/${id}`, newObject)
                                                                                                        return request.then(response => response.data)
                                                                                                      }
                                                                                                      
                                                                                                      const remove = (id) => {
                                                                                                        const request = axios.delete(`${baseUrl}/${id}`)
                                                                                                        return request.then(res => res.data)
                                                                                                      }
                                                                                                      
                                                                                                      export default { getAll, create, update, remove, baseUrl }
                                                                                                      

                                                                                                      My json-server "db.json"

                                                                                                      {
                                                                                                        "numbers": [
                                                                                                          {
                                                                                                            "name": "uvaldo",
                                                                                                            "number": "20",
                                                                                                            "id": 6
                                                                                                          },
                                                                                                          {
                                                                                                            "name": "uvaldo zumaya",
                                                                                                            "number": "24",
                                                                                                            "id": 7
                                                                                                          },
                                                                                                          {
                                                                                                            "name": "uvaldo zumaya d",
                                                                                                            "number": "26",
                                                                                                            "id": 8
                                                                                                          }
                                                                                                        ]
                                                                                                      }
                                                                                                      

                                                                                                      Whenever I try to update "uvaldo" phone number to 22, it just stays at 21 then throws errors, this picture is before I hit "add" to avoid the program crashing...

                                                                                                      https://i.stack.imgur.com/CD2rh.png

                                                                                                      ANSWER

                                                                                                      Answered 2022-Apr-18 at 01:06

                                                                                                      There are issues with the logic where you update persons.

                                                                                                      Try this instead:

                                                                                                        const handleSubmit = (e) => {
                                                                                                      ...
                                                                                                              const indexFinder = persons.findIndex(person => person.name === newName)
                                                                                                              newObj.id = persons[indexFinder].id
                                                                                                              copy[indexFinder] = newObj
                                                                                                              phoneService.update(persons[indexFinder].id, newObj)
                                                                                                              .then(res => {
                                                                                                                setErrorMessage(`Successfully updated ${newName}s number`)
                                                                                                                setPersons(copy)})
                                                                                                      ...
                                                                                                        }
                                                                                                      

                                                                                                      The reason why it was adding empty elements is that the index used to place newObj was greater than the size of the array:

                                                                                                      copy[indexFinder[0].id] = newObj
                                                                                                      

                                                                                                      Also note that person.id does not necessarily mean that they are in that index of the array persons.

                                                                                                      Source https://stackoverflow.com/questions/71906478

                                                                                                      QUESTION

                                                                                                      trying to make "npm run dev" create 2 shell instances
                                                                                                      Asked 2022-Mar-23 at 11:29

                                                                                                      I'm using json-server as my local server for a nuxt project and i want to automatically launch the server and then run the project on another shell instance using "npm run dev"

                                                                                                      in the scripts tag in package.json this is what i came up with :

                                                                                                          "dev": "json-server --watch db.json --port 3004 & nuxt"
                                                                                                      

                                                                                                      but this script only starts the server

                                                                                                      ANSWER

                                                                                                      Answered 2022-Mar-23 at 11:29
                                                                                                      npm install -g concurrently
                                                                                                      

                                                                                                      "dev": "concurrently \"json-server --watch db.json --port 3004\" \"nuxt""

                                                                                                      Source https://stackoverflow.com/questions/71586362

                                                                                                      QUESTION

                                                                                                      json-server running but can't access its api due to 403
                                                                                                      Asked 2022-Mar-21 at 23:02

                                                                                                      Learning reactjs, trying to simulate a server with json-server
                                                                                                      this is my script to run the server:

                                                                                                      "scripts": {
                                                                                                          "server": "json-server --watch db.json --port 5000"
                                                                                                      },
                                                                                                      

                                                                                                      running this on terminal npm run server
                                                                                                      output:

                                                                                                      Debugger listening on ws://127.0.0.1:61616/507f7893-92a9-4526-b8f4-a3e71cfa4c62
                                                                                                      For help, see: https://nodejs.org/en/docs/inspector
                                                                                                      Debugger attached.
                                                                                                      
                                                                                                      > my-app@0.1.0 server
                                                                                                      > json-server --watch db.json --port 5000
                                                                                                      
                                                                                                      Debugger listening on ws://127.0.0.1:61629/8a2f877f-f4bd-465e-b454-01a63eabb40a
                                                                                                      For help, see: https://nodejs.org/en/docs/inspector
                                                                                                      Debugger attached.
                                                                                                      
                                                                                                        \{^_^}/ hi!
                                                                                                      
                                                                                                        Loading db.json
                                                                                                        Done
                                                                                                      
                                                                                                        Resources
                                                                                                        http://localhost:5000/tasks
                                                                                                      
                                                                                                        Home
                                                                                                        http://localhost:5000
                                                                                                      
                                                                                                        Type s + enter at any time to create a snapshot of the database
                                                                                                        Watching...
                                                                                                      

                                                                                                      now when I try to access http://localhost:5000/tasks , I get 403 Access to localhost was denied.
                                                                                                      what can I do to fix this?
                                                                                                      Thanks!

                                                                                                      ANSWER

                                                                                                      Answered 2021-Dec-18 at 13:15

                                                                                                      the problem was with the port. changed it to 3001 and it works. still doesn't understand why did this happen in that port.

                                                                                                      Source https://stackoverflow.com/questions/70401937

                                                                                                      QUESTION

                                                                                                      I trying to json-server by npm install -g json-server, but everytime I get an error
                                                                                                      Asked 2022-Mar-03 at 07:01

                                                                                                      Image of the error This is the error that I am continuously getting after numerous tries. I tried removing node cache, I re-installed node.js but couldn't find success. However, whenever I am running it with administrator or root, I am able to install it. So why is this happening?

                                                                                                      I have provided the screenshot of my error, however, still, I will provide the error in writing.

                                                                                                      npm ERR! code EPERM
                                                                                                      npm ERR! syscall mkdir
                                                                                                      npm ERR! path C:\Program Files\nodejs\node_modules\json-server
                                                                                                      npm ERR! errno -4048
                                                                                                      npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\json-server'
                                                                                                      npm ERR!  [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\json-server'] {
                                                                                                      npm ERR!   errno: -4048,
                                                                                                      npm ERR!   code: 'EPERM',
                                                                                                      npm ERR!   syscall: 'mkdir',
                                                                                                      npm ERR!   path: 'C:\\Program Files\\nodejs\\node_modules\\json-server'
                                                                                                      npm ERR! }
                                                                                                      npm ERR!
                                                                                                      npm ERR! The operation was rejected by your operating system.
                                                                                                      npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
                                                                                                      npm ERR! or that you lack permissions to access it.
                                                                                                      npm ERR!
                                                                                                      npm ERR! If you believe this might be a permissions issue, please double-check the
                                                                                                      npm ERR! permissions of the file and its containing directories, or try running
                                                                                                      npm ERR! the command again as root/Administrator.
                                                                                                      
                                                                                                      npm ERR! A complete log of this run can be found in:
                                                                                                      npm ERR!     C:\Users\7386-85615SG 2913642\AppData\Local\npm-cache\_logs\2021-09-03T06_29_38_211Z-debug.log
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2021-Sep-03 at 07:58

                                                                                                      Try running this command: npm config set unsafe-perm=true

                                                                                                      If that doesn't work for you, try changing the folder permissions for your current user for C:\Program Files\nodejs with the help of this

                                                                                                      Source https://stackoverflow.com/questions/69040511

                                                                                                      QUESTION

                                                                                                      json-server returns HTTP 200 instead of 404 for query parameter filtered GET request, what is the best practice here & how can 404 be returned?
                                                                                                      Asked 2022-Feb-24 at 18:42
                                                                                                      Context

                                                                                                      Attempting to make a HTTP GET request for posts filtered by query parameter authorId=x where x may be a number that may not correspond to any post's authorId.

                                                                                                      Problem

                                                                                                      json-server unexpectedly returns HTTP 200 instead of HTTP 404 response when there are no posts with a matching authorId (i.e., an empty array is returned), how can this be changed to return 404? Similarly, what would be the best API practice here, would it be to return an empty array with HTTP 400 as json-server already does or would returning the empty array with HTTP 404 be more clear for users?

                                                                                                      I've looked at jsonServer.rewriter & express middleware (e.g., json-server documentation shows it can be configured with middleware such as server.use(middlewares)) but wanted to ask what the best approach would be here (useful resources/links would be appreciated here), e.g., with middleware, an option is sending 404 for an empty array but does json-server have an builtin ways to handle this or is there a better approach?

                                                                                                      All constructive feedback is welcome, thanks.

                                                                                                      Code

                                                                                                      db.json:

                                                                                                      {
                                                                                                          "posts": [
                                                                                                              {
                                                                                                                  "authorId": 0,
                                                                                                                  "content": "Foo bar"
                                                                                                              },
                                                                                                          ],
                                                                                                      }
                                                                                                      

                                                                                                      Shell:

                                                                                                      json-server --watch db.json
                                                                                                      

                                                                                                      REST:

                                                                                                      // Response status is expected HTTP 200.
                                                                                                      GET http://localhost:5000/posts?authorId=0
                                                                                                      

                                                                                                      This returns the user with HTTP 200 as expected:

                                                                                                      [
                                                                                                        {
                                                                                                            "authorId": 0,
                                                                                                            "content": "Foo bar",
                                                                                                        }
                                                                                                      ]
                                                                                                      
                                                                                                      // Response status is unexpected HTTP 200 but 404 was expected since response body contains an empty array. This is the problem.
                                                                                                      GET http://localhost:5000/posts?authorId=does_not_exist
                                                                                                      

                                                                                                      This returns an empty array with HTTP 200, which is possibly unexpected (uncertain on what the best practice is regarding filtered collections where there's no match, but what would be the best practice here & how can the status be changed to HTTP 400:

                                                                                                      []
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2022-Feb-24 at 18:42

                                                                                                      As @kindall pointed out, probably ill-advised to return 404, but perhaps this is the existing behavior of the API you're mocking. You can return custom output - from docs: https://github.com/typicode/json-server#custom-output-example

                                                                                                      // In this example we simulate a server side error response
                                                                                                      router.render = (req, res) => {
                                                                                                        res.status(500).jsonp({
                                                                                                          error: "error message here"
                                                                                                        })
                                                                                                      }
                                                                                                      

                                                                                                      For your example, it would probably be something like (untested pseudo-code):

                                                                                                      // In this example we return 404 for no content
                                                                                                      router.render = (req, res) => {
                                                                                                        if (res.locals.data.posts.length < 1) {
                                                                                                          res.status(404).jsonp({
                                                                                                            error: "no posts"
                                                                                                          });
                                                                                                        } else {
                                                                                                          res.jsonp(res.locals.data);
                                                                                                        }
                                                                                                      }
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/70279926

                                                                                                      QUESTION

                                                                                                      How to use json-server | Getting 404 for local db.json
                                                                                                      Asked 2021-Dec-20 at 03:10

                                                                                                      I'm pretty sure doing everything correctly. I'm using these version:

                                                                                                      "axios": "^0.24.0",
                                                                                                      "json-server": "^0.17.0",
                                                                                                      

                                                                                                      I've followed the official doc. I've db.json in the root folder itself.

                                                                                                      {
                                                                                                      "users": [
                                                                                                          {
                                                                                                            "ID": 1,
                                                                                                            "Username": "mike",
                                                                                                            "Password": "User1Password"
                                                                                                          },
                                                                                                          {
                                                                                                            "ID": 2,
                                                                                                            "Username": "robert",
                                                                                                            "Password": "User2Password"
                                                                                                          }
                                                                                                        ]
                                                                                                      }
                                                                                                      

                                                                                                      I'm running json-server with this command: json-server --watch db.json --port 4000

                                                                                                      Whenever I hit http://localhost:4000/users I'm served with this:

                                                                                                        \{^_^}/ hi!
                                                                                                      
                                                                                                        Loading db.json
                                                                                                        Done
                                                                                                      
                                                                                                        Resources
                                                                                                        http://localhost:4000/posts
                                                                                                        http://localhost:4000/comments
                                                                                                        http://localhost:4000/profile
                                                                                                      
                                                                                                        Home
                                                                                                        http://localhost:4000
                                                                                                      
                                                                                                        Type s + enter at any time to create a snapshot of the database
                                                                                                        Watching...
                                                                                                      
                                                                                                        GET /users 404 4.800 ms - 2
                                                                                                      

                                                                                                      But rest of the end points like:

                                                                                                      http://localhost:4000/posts
                                                                                                      http://localhost:4000/comments
                                                                                                      http://localhost:4000/profile
                                                                                                      

                                                                                                      are working absolutely fine. Please help.

                                                                                                      ANSWER

                                                                                                      Answered 2021-Oct-30 at 03:31

                                                                                                      According to @user2740650
                                                                                                      You said db.json is in src folder. What matters is that it's in the same folder where you started the server. It sounds like it created a default db.json somewhere else and is using that.

                                                                                                      Second Scenario
                                                                                                      move your db.json file into the Public folder and calling it by: axios.get('db.json') .then(//...)

                                                                                                      Source https://stackoverflow.com/questions/69776406

                                                                                                      QUESTION

                                                                                                      Can't install json-server
                                                                                                      Asked 2021-Nov-23 at 13:06

                                                                                                      I am trying to install JSON-Server, but it's not working!

                                                                                                      I have used the following command: npm install -g json-server

                                                                                                      Here is the error message:

                                                                                                      npm ERR! code EACCES
                                                                                                      npm ERR! syscall mkdir
                                                                                                      npm ERR! path /usr/local/lib/node_modules/json-server
                                                                                                      npm ERR! errno -13
                                                                                                      npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/json-server'
                                                                                                      npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/json-server'] {
                                                                                                      npm ERR!   errno: -13,
                                                                                                      npm ERR!   code: 'EACCES',
                                                                                                      npm ERR!   syscall: 'mkdir',
                                                                                                      npm ERR!   path: '/usr/local/lib/node_modules/json-server'
                                                                                                      npm ERR! }
                                                                                                      npm ERR! 
                                                                                                      npm ERR! The operation was rejected by your operating system.
                                                                                                      npm ERR! It is likely you do not have the permissions to access this file as the current user
                                                                                                      npm ERR! 
                                                                                                      npm ERR! If you believe this might be a permissions issue, please double-check the
                                                                                                      npm ERR! permissions of the file and its containing directories, or try running
                                                                                                      npm ERR! the command again as root/Administrator.
                                                                                                      
                                                                                                      

                                                                                                      ANSWER

                                                                                                      Answered 2021-Nov-23 at 13:06

                                                                                                      Try to use sudo before command :

                                                                                                      sudo npm install -g json-server

                                                                                                      Source https://stackoverflow.com/questions/70081261

                                                                                                      QUESTION

                                                                                                      Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app
                                                                                                      Asked 2021-Nov-18 at 09:05

                                                                                                      I have installed the json-server in my Angular app which enables me to save a form (filled by the user) via a fake json API into a json file:

                                                                                                      {
                                                                                                        "extracts": [
                                                                                                          {
                                                                                                            "contentName": "xxx",
                                                                                                            "contentType": "xxx",
                                                                                                            "contentToStore": "xxx",
                                                                                                            "id": 1
                                                                                                          }
                                                                                                        ]
                                                                                                      }
                                                                                                      

                                                                                                      I can also see the results at my http://localhost:3000/extracts

                                                                                                      In my html template, my form is submitted:

                                                                                                      
                                                                                                      

                                                                                                      In the corresponding component, I have written this code:

                                                                                                      onSubmitExtractions(postData: Post) {
                                                                                                          
                                                                                                          this
                                                                                                            .dbService
                                                                                                            .submitExtractions(postData)
                                                                                                            .subscribe(
                                                                                                              postData => {
                                                                                                                this.jsonPosts.push(postData);
                                                                                                              }
                                                                                                          );
                                                                                                          
                                                                                                          this
                                                                                                            .dbService
                                                                                                            .downloadExtractions(postData);
                                                                                                      }
                                                                                                      

                                                                                                      The first snippet writes to the json file, with this code in the service script:

                                                                                                      submitExtractions(post: Post): Observable {
                                                                                                          return this.httpClient.post(this.apiUrl, post, httpOptions);
                                                                                                      }
                                                                                                      

                                                                                                      This works fine and I get the results in a json file (fake json server database) and the second snippet is supposed to download this file whose code in the service script is this:

                                                                                                      downloadExtractions(post: Post) {
                                                                                                      
                                                                                                          const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });
                                                                                                      
                                                                                                          if (blob) {
                                                                                                            this.downloaded = 'The blob contains ' + blob.size + ' byte!';
                                                                                                          } else {
                                                                                                            this.downloaded = 'The download failed!';
                                                                                                          }
                                                                                                      }
                                                                                                      

                                                                                                      What am I missing in ths code in order to actually download the json content? How do I download this content as a csv or json or even a text file?

                                                                                                      ANSWER

                                                                                                      Answered 2021-Oct-13 at 09:21

                                                                                                      Please try this solution. It is using the same blob just with some constant data.

                                                                                                      in html

                                                                                                      in component.ts

                                                                                                      export class AppComponent implements OnInit {
                                                                                                        name = 'Angular 5';
                                                                                                        fileUrl;
                                                                                                        constructor(private sanitizer: DomSanitizer) {  }
                                                                                                        ngOnInit() {
                                                                                                          const data = 'some text';
                                                                                                          const blob = new Blob([data], { type: 'application/octet-stream' });
                                                                                                      
                                                                                                          this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
                                                                                                        }
                                                                                                      
                                                                                                      }
                                                                                                      

                                                                                                      Source https://stackoverflow.com/questions/69551610

                                                                                                      QUESTION

                                                                                                      In ' "db": "json-server -w db.json -p 3001" ', what is '-w' in here means?
                                                                                                      Asked 2021-Nov-17 at 20:28

                                                                                                      what is -w in here means ?

                                                                                                      "db": "json-server -w db.json -p 3001"
                                                                                                      

                                                                                                      this is the package .json file

                                                                                                      
                                                                                                      {
                                                                                                        "name": "jsonserver",
                                                                                                        "version": "1.0.0",
                                                                                                        "description": "",
                                                                                                        "main": "index.js",
                                                                                                        "scripts": {
                                                                                                          "db": "json-server -w db.json -p 3001",
                                                                                                          "tunnel": "ngrok http 3001"
                                                                                                        },
                                                                                                        "author": "",
                                                                                                        "license": "ISC",
                                                                                                        "dependencies": {
                                                                                                          "axios": "^0.24.0",
                                                                                                          "json-server": "^0.17.0",
                                                                                                          "ngrok": "^4.2.2"
                                                                                                        }
                                                                                                      }
                                                                                                      
                                                                                                      

                                                                                                      and i am doing this for a react-native project what does -w means?

                                                                                                      ANSWER

                                                                                                      Answered 2021-Nov-16 at 09:23

                                                                                                      QUESTION

                                                                                                      Is there a way to run server with a session-persisted database connection in Django?
                                                                                                      Asked 2021-Nov-16 at 11:12

                                                                                                      As I develop the backend side, I also develop the frontend. As you have probably guessed, I have to do some REST requests on my server.

                                                                                                      Well, there are a couple of solutions for that. I can use mocks on the frontend, or a fake JSON server. However, there are some cons to this approach:

                                                                                                      • I have to remodel what I have on an already existing backend server.
                                                                                                      • Dealing with authentication on a fake JSON server is not really comfortable.
                                                                                                      • I have to write a lot of boilerplate if I want to go on mocking and unit testing approach.

                                                                                                      Again, all the logic I want already exists in my Django project, so what I want is:

                                                                                                      1. Run a dev server.
                                                                                                      2. Set up a fresh new database.
                                                                                                      3. Provide some initial data. Some fake users, posts, whatever.
                                                                                                      4. Do my testing on my frontend project while the server runs.
                                                                                                      5. Hit the kill signal. (CTRL+C)
                                                                                                      6. Gracefully drop the database that I have created on step 2.
                                                                                                      7. Shutdown the program.

                                                                                                      I use pytest and pytest-django. They do exactly these when they set up a test environment, I was wondering if I can manually do that.

                                                                                                      Thanks in advance.

                                                                                                      Environment
                                                                                                      • Python 3.9
                                                                                                      • Django 2.2

                                                                                                      ANSWER

                                                                                                      Answered 2021-Nov-16 at 11:12

                                                                                                      I never used such integration-testing setup, but I’ve seen it somewhere.

                                                                                                      You can run the django-admin testserver mydata.json command to spin up a testing server with data from a provided fixture. The way it was done in the example I saw was by making a custom Django command where instead of static fixture the testserver’s database was populated dynamically by factories. I don’t remember the details how it was implemented, though.

                                                                                                      After the testserver was ready, the Cypress tests were run. Backend and the frontend were wired by npm’s start-server-and-test package.

                                                                                                      Application with similar setup can be checked out here. Especially note the custom testserver command as well as the cypress commands.

                                                                                                      Source https://stackoverflow.com/questions/69987275

                                                                                                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                                      Vulnerabilities

                                                                                                      No vulnerabilities reported

                                                                                                      Install json-server

                                                                                                      Create a db.json file with some data. Now if you go to http://localhost:3000/posts/1, you'll get.
                                                                                                      If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to db.json using lowdb.
                                                                                                      Your request body JSON should be object enclosed, just like the GET output. (for example {"name": "Foobar"})
                                                                                                      Id values are not mutable. Any id value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken.
                                                                                                      A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will return a 2XX status code, but without changes being made to the data.

                                                                                                      Support

                                                                                                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                                      Find more information at:
                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit
                                                                                                      Install
                                                                                                    • npm

                                                                                                      npm i json-server

                                                                                                    • CLONE
                                                                                                    • HTTPS

                                                                                                      https://github.com/typicode/json-server.git

                                                                                                    • CLI

                                                                                                      gh repo clone typicode/json-server

                                                                                                    • sshUrl

                                                                                                      git@github.com:typicode/json-server.git

                                                                                                    • Share this Page

                                                                                                      share link

                                                                                                      Explore Related Topics

                                                                                                      Consider Popular REST Libraries

                                                                                                      public-apis

                                                                                                      by public-apis

                                                                                                      json-server

                                                                                                      by typicode

                                                                                                      iptv

                                                                                                      by iptv-org

                                                                                                      fastapi

                                                                                                      by tiangolo

                                                                                                      beego

                                                                                                      by beego

                                                                                                      Try Top Libraries by typicode

                                                                                                      husky

                                                                                                      by typicodeJavaScript

                                                                                                      lowdb

                                                                                                      by typicodeJavaScript

                                                                                                      hotel

                                                                                                      by typicodeJavaScript

                                                                                                      jsonplaceholder

                                                                                                      by typicodeHTML

                                                                                                      tlapse

                                                                                                      by typicodeJavaScript

                                                                                                      Compare REST Libraries with Highest Support

                                                                                                      fastapi

                                                                                                      by tiangolo

                                                                                                      dropwizard

                                                                                                      by dropwizard

                                                                                                      python

                                                                                                      by kubernetes-client

                                                                                                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                                      Find more libraries
                                                                                                      Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                                      Save this library and start creating your kit