http-proxy-middleware 简单代理服务器

前言

在现在前后端分离开发模式中,API接口成了,连接前后台的重要一步, 而开发中前台请求受同源策略的限制,会出现跨域的问题,有很多解决跨域的方法,其实每个公司都会使用统一的一种, 我们使用的vue框架,所以直接配置就行。
但还有些jquery项目需要调试。

package.json

利用express和http-proxy-middleware来写,依赖如下

{
  "name": "expressProxy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "connect-timeout": "^1.9.0",
    "express": "^4.16.4",
    "http-proxy-middleware": "^0.19.1"
  }
}
复制代码

index.js

/*
 express + http-proxy-middleware 代理请求
 */
const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();
// 本服务端口
const PORT = 9527
// cookie写入地址
const cookieUrl = '127.0.0.1'
// PORT 服务端口
const  kandao =  { 
  target : 'http://125.44.97.88:8900',
  changeOrigin: true,
  cookieDomainRewrite: {
    "*": cookieUrl // 把相应的 cookie 域都设置成 localhost
  },
  ws: true,
  withCredentials: true,
 }

// 超时时间
const TIME_OUT = 30 * 1e3;

// 设置端口

// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
//设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Access-Control-Allow-Headers,Authorization,Origin,Accept,Power-By,x-token-id");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", true);
  res.header("accept",'image/webp,image/apng,image/*,*/*;q=0.8')
  // res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
app.use((req, res, next) => {
  if (!req.timedout) next();
});
// 看到代理
app.use(proxy('/cms', { ...kandao }));

// 监听端口
app.listen(PORT, () => {
  console.log(`启动代理服务器=> http://127.0.0.1:${PORT}`);
});
复制代码

执行

npm run dev
复制代码

前台请求

let url = 'http://127.0.0.1:9527'
$.ajax(
 {
     url,
     // 如果请求需自动带上cookie
     type: 'GET',
     xhrFields: {
         withCredentials: true
     },
     crossDomain: true,
     success () {}
 }
)
复制代码

转载于:https://juejin.im/post/5cc0378cf265da039444ada1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值