今天把项目中的反向代理脚本程序抽成了一个插件,经过配置文件配置代理的http请求,这样使用起来比较方便,每位开发成员均可以用本身配置的代理调试代码。也能够用来直接作http代理,你甚至都不用Charles或者fiddler,直接开启proxy-ajax,而后手机上设置代理就能够了。javascript
proxy-ajax: https://github.com/chalecao/proxy-ajax
欢迎你们试用,给我点颗星星哈。php
npm install proxy-ajax -g -------you can specify the config file path and port--- proxy-ajax ./.proxy-ajax.config -p 80 ------- you can use the default config path and port--- proxy-ajax
默认配置文件: ./.proxy-ajax.config.js 默认代理端口: 80java
配置文件示例:jquery
.proxy-ajax.config.js file:
--------------------------
export default { "port": 8889, //"httpsPort": 8890, //"cert": "", //https cert //"key": "", //https key "target-mtop": "https://x.x.x.x/", "target-other": "http://baidu.com", "proxy": [{ "host": ["localhost:8889", "api.baidu.com"], "rule": [{ "path": "getBaidu", "routeTo": "target-mtop" }], "otherRouteTo": "target-other" }] }
若是你不想写不少的配置文件,你能够把代理的配置写到其余的配置文件里,须要添加proxyConfig属性就能够了,示例以下:git
xxxx.config.js file:
--------------------------
var data = require("./data") export default { ..... ..... proxyConfig:{ "port": 8889, // "httpsPort": 8890, "target-page": "http://127.0.0.1:3000/", "target-mtop": "https://x.x.x.x/", "target-static": "http://127.0.0.1:8000", "proxy": [{ "path": "/h5/", "target": "target-mtop" },{ "path": "/h5/jianribimai", "data": "./src/demo/data/new3.js" },{ "path": "/h5/test", "data": JSON.stringify(data) }] } .... }
这里顺带介绍一下这个知识点,跨域请求经常使用的方案是CORS,常常会遇到跨域请求带cookie的状况,默认ajax跨域请求是不带cookie的。若是须要带cookie,须要这样写:github
原生ajax请求方式:
var xhr = new XMLHttpRequest(); xhr.open("POST", "http://xxxx.com/demo/b/index.php", true); xhr.withCredentials = true; //支持跨域发送cookies xhr.send(); jquery为例: $.ajax({ type: "POST", url: "http://xxx.com/api/test", dataType: 'jsonp', xhrFields: { withCredentials: true //配置跨域带cookie }, crossDomain: true, success:function(){ }, error:function(){ } })
服务端CORS配置:ajax
1
2
|
header(“Access-Control-Allow-Credentials: true”); //容许跨域带cookie
header(“Access-Control-Allow-Origin: http://www.xxx.com”); //容许跨域请求的域名
|
正向代理,只用于代理内部网络对Internet的链接请求,客户机必须指定代理服务器,并将原本要直接发送到Web服务器上的http请求发送到代理服务器中。此时正向代理表现的像一个客户端,请求资源,返回数据。sql
反向代理(Reverse Proxy)方式是指以代理服务器来接受Internet上的链接请求,而后将请求转发给内部网络上的服务器;并将从服务器上获得的结果返回给Internet上请求链接的客户端,此时代理服务器对外就表现为一个服务器,代理请求。npm