nodejs构建mock数据

Nodejs构建mock数据并通过rest api风格调用接口访问数据

如果我们只有json格式的数据文件,我们想通过访问url方式调用居然数据

 

确保电脑安装node环境

如果你没有安装好node环境请移步http://nodejs.cn/

 一、安装json-server

 1.新建demo文件

cd demo

 2.安装json-server

 

npm install -S json-server

 

3.项目demo目录下,新建一个 JSON 文件data.json和一个package.json文件

db.json内容如下

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

 

package.json内容如下

 

{

  "name": "rest-api-demo",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "server": "json-server data.json",

    "test": "..."

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "dependencies": {

    "json-server": "^0.9.4"

  }

}

 

二、启动服务

npm run server

 

三、调用rest 风格api

打开浏览器

 

 

注意这个的数据获取只是get方式请求获取到的,如需POSTPUTDELETE等 HTTP 方法的数据体进行解析请参考

https://github.com/ruanyf/jstraining/tree/master/demos#rest-api

 

posted @ 2017-02-11 20:31  若强  Views(7093)  Comments(0Edit  收藏  举报