nginx配置 前端反向代理
前言
因为需要本地开发模拟线上环境,所以应用json-server mock数据通过nginx配置反向代理反向代理,通过修改host 来绑定域名。通过查找多篇文档配置成功。
下载nginx
因为我是mac环境下开发,所有用brew下载
$ brew install nginx
# 安装完成后会看到
# /usr/local/etc/nginx/nginx.conf 配置
# /usr/local/etc/nginx/servers/ 服务区默认路径
# /usr/local/Cellar/nginx/1.10.1 安装路径
# 推荐一个快捷键 command+shift+g 前往文件夹
Nginx 默认8080端口,
这时已经可以访问了:localhost:8080
如果成功就会看到 nginx的欢迎页面
配置nginx
打开/usr/local/etc/nginx/nginx.conf 文件
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http{
server {
//监听端口号
listen 80;
//反向代理的域名
server_name www.baidu.com;
location / {
//本地模拟服务器地址及端口
proxy_pass http://127.0.0.1:8888/;
}
}
}
修改本机host
$ sudo vi /etc/hosts
# 输入自己的密码
# 按 i进入插入模式
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
#百度 本机模拟数据的ip
127.0.0.1 www.baidu.com
启动服务
# 启动服务
$ sudo nginx
# 停止服务
$ sudo nginx -S stop
此时nginx的基本搭建已经完成
json-server与faker 搭建与使用
# 下载json-server
$ npm install -g json-server
# 安装不成功 用管理权限 sudo
# sudo npm install -g json-server
任意路径创建一个文件夹
# 执行
$ npm install faker lodash -S
创建一个文件generate.js(名字是什么不重要)
//generate.js文件
module.exports = function(){
var faker =require('faker');
var lodash = require('lodash');
return {
people: lodash.times(100,function (n) {
return {
id: n,
name: faker.name.findName(),
avatar: faker.internet.avatar(),
img: faker.image.image(),
text: faker.lorem.text()
}
})
}
}
# 启动json-server 服务
# 端口号默认3000
# 通过 -p 可以修改端口号
$ json-server generate.js -p 3004
此时可以通过 http://localhost:3004/people 来访问刚刚模拟的数据了
json-server 常用方法集合
查询(get)
查询全部
http://localhost:3004/people
查询单条
http://localhost:3004/people/1
#这里 1 为id
http://localhost:3004/people?id=1
# 此种方法可以查任意字段 如 name=name
查询多条
http://localhost:3004/people?id=1&id=2
#查询结果为 id为1和id为2的数据
http://localhost:3004/people?_start=0&_end=20
# 查询0条到20条
http://localhost:3004/people?_start=0&_limit=10
#查询从0开始向后取10条
过滤
http://localhost:3004/people?id_ne=1
#显示排除id=1的所有数据
http://localhost:3004/people?q=Aufderhar
#q= 全文搜索
插入数据(post)
插入数据
header设置 Content-Type:application/json
数据格式为json字符串
例如:JSON.stringify({"title":"title"})
使用post请求后 回调结果为{id:100,title:title} 则成功插入
删除数据(DELETE)
单个删除数据
method:DELETE
url:http://localhost:3004/people/100
单个修改数据
method:put
url:http://localhost:3004/people/100
猎巫文章地址(有部分借鉴)
关于faker.js模拟数据
faker.js
使用方法(只描述一种 具体请看文档)
-
address
- zipCode
- city
- cityPrefix
- citySuffix
- streetName
- streetAddress
- streetSuffix
- streetPrefix
- secondaryAddress
- county
- country
- countryCode
- state
- stateAbbr
- latitude
- longitude
例如我们需要模拟城市名称则这样做
fker.address.city()
fker | address | city |
---|---|---|
require进来的方法 | 分类 现在为address具体请看文档 | address下的方法 |
详情查看官方文档 |