分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

基于node开发的http请求代理

发布时间:2023-09-06 01:08责任编辑:林大明关键词:http

今天把项目中的反向代理脚本程序抽成了一个插件,通过配置文件配置代理的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; //支持跨域发送cookiesxhr.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请求代理

原文地址:http://www.cnblogs.com/chero/p/7474400.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved