Nodejs-npm包之http-server和json-server

来源:互联网 发布:工期优化步骤 编辑:程序博客网 时间:2024/05/22 05:18

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 打印以上列表并退出
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 春羽叶子长黄斑怎么办 百合竹叶子发黄掉落怎么办 凤尾蕨叶子蔫了怎么办 绿地珊瑚蕨干了怎么办 翠云草叶子蔫了怎么办 珊瑚蕨叶子烂了怎么办 黑骨茶叶子黑斑怎么办 外场主持没有人互动怎么办 企业年报填错了怎么办 手机忘了放哪了怎么办 燃气卡车没气了怎么办 老房子拆了重建怎么办 加了差的汽油怎么办 事业单位未满5年怎么办 小学孩子不会制订学习计划怎么办 忘记提交原创怎么办百度熊掌号 计算机一级报名表填错了怎么办 离婚了不给孩子生活费怎么办 点击爱奇艺系统提示停止运行怎么办 电视机图像颜色变了怎么办 10万签约被拒怎么办 钢琴弹奏中的折指怎么办! 吉他琴头旋钮将琴头扭坏了怎么办? 1岁幼儿不爱吃饭怎么办 3岁幼儿不爱吃饭怎么办 4岁幼儿不爱吃饭怎么办 买票买了点映 怎么办 一年级孩子注意力不集中怎么办 孩子上一年级注意力不集中怎么办 普宁二中初一新生住宿怎么办 小学入学普查错过了怎么办 初一的孩子不爱学习怎么办 初一孩子出现厌学情况怎么办 客人要求我们代办事项时怎么办 客人要求我们代办事项应该怎么办 想家了特别想哭怎么办 把友谊看得太重怎么办 高一新生数学差怎么办 如果好朋友觉得你成熟阴暗怎么办 被同学抓住把柄敲诈怎么办 初一学生字写的不好怎么办