Nodejs安装
去http://nodejs.cn/下载即可
Windows/Linux都行,此处省略
不懂的可以看如下传送门:
http://www.runoob.com/nodejs/nodejs-install-setup.html
安装cnpm
国内的npm网速实在是捉急,也多亏了阿里巴巴,可以使用阿里巴巴的cnpm
建议使用-g全局安装,这样在别的地方也可以使用该命令
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
安装完毕后,可直接使用cnpm代替npm命令,cnpm会优先去alibaba里面的CDN找有没有这个文件,没有的话,再帮你转换成npm命令
npm插件
json-server
https://github.com/typicode/json-server
安装:
cnpm install -g json-server
安装完毕后,创建一个json文件,如:db.json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
启动
$ json-server --watch db.json
浏览器访问:http://localhost:3000/posts/1
结果:
{ "id": 1, "title": "json-server", "author": "typicode" }
修改端口
端口是使用了express的默认端口,修改端口
$ json-server --watch db.json --port 3004
结果npm的init以后在package.json一起使用,则是直接在package.json改成
{
"name": "rest-api-demo",
"version": "1.0.0",
"description": "Nick's NPM APP",
"main": "index.js",
"scripts": {
"server": "json-server db.json",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Nick",
"license": "ISC"
}
只需要在”scripts”中加上"server": "json-server db.json"
优点:
前端不需要等后端的json才能测试,直接自己本地构建一个json的server即可
能够自动根据json文件构建基于RESTFUL接口,与后端天然对应
http-server
http-server也是类似json-server,只不过http-server是用来将本地的文件转成文件
https://github.com/indexzero/http-server
安装:
cnpm install http-server -g
启动:
http-server
浏览器可访问http://localhost:8080/
常用参数:
-p 端口号 (默认 8080)
-a IP 地址 (默认 0.0.0.0)
-d 显示目录列表 (默认 'True')
-i 显示 autoIndex (默认 'True')
-e or --ext 如果没有提供默认的文件扩展名(默认 'html')
-s or --silent 禁止日志信息输出
--cors 启用 CORS via the Access-Control-Allow-Origin header
-o 在开始服务后打开浏览器
-c 为 cache-control max-age header 设置Cache time(秒) , e.g. -c10 for 10 seconds (defaults to '3600'). 禁用 caching, 则使用 -c-1.
-U 或 --utc 使用UTC time 格式化log消息
-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com
-S or --ssl 启用 https
-C or --cert ssl cert 文件路径 (default: cert.pem)
-K or --key Path to ssl key file (default: key.pem).
-r or --robots Provide a /robots.txt (whose content defaults to 'User-agent: *\nDisallow: /')
-h or --help 打印以上列表并退出