基於node開發的http請求代理
阿新 • • 發佈:2017-09-04
oss .... http請求 代理 test 寫到 pan eve 常用
今天把項目中的反向代理腳本程序抽成了一個插件,通過配置文件配置代理的http請求,這樣使用起來比較方便,每位開發成員都可以用自己配置的代理調試代碼。
git
proxy-ajax: https://github.com/chalecao/proxy-ajax
歡迎大家試用,給我點顆星星哈。
用法:
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 默認代理端口: 80
配置文件示例:
.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屬性就可以了,示例如下:
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)
}]
}
....
}
ajax請求跨域帶cookie
這裏順帶介紹一下這個知識點,跨域請求常用的方案是CORS,經常會遇到跨域請求帶cookie的情況,默認ajax跨域請求是不帶cookie的。如果需要帶cookie,需要這樣寫:
原生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配置:
1 2 | header(“Access-Control-Allow-Credentials: true”); //允許跨域帶cookie header(“Access-Control-Allow-Origin: http://www.xxx.com”); //允許跨域請求的域名 |
反向代理與正向代理
正向代理,只用於代理內部網絡對Internet的連接請求,客戶機必須指定代理服務器,並將本來要直接發送到Web服務器上的http請求發送到代理服務器中。此時正向代理表現的像一個客戶端,請求資源,返回數據。
反向代理(Reverse Proxy)方式是指以代理服務器來接受Internet上的連接請求,然後將請求轉發給內部網絡上的服務器;並將從服務器上得到的結果返回給Internet上請求連接的客戶端,此時代理服務器對外就表現為一個服務器,代理請求。
謝謝!
基於node開發的http請求代理