vue项目的反向代理

文章介绍了前端因浏览器同源策略无法直接发送跨域请求,故采用反向代理解决此问题。重点讲解了使用http-proxy-middleware和http-proxy两个库在Node.js环境中设置反向代理的步骤,包括安装、主要API及配置选项,如目标URL、路径重写和跨域设置。同时提到了http代理和websocket代理的实现。
摘要由CSDN通过智能技术生成
背景:前端代码在浏览器里面运行,由于浏览器的同源策略,不能直接发送跨域请求,所以,前端要做一个反向代理,解决跨域问题
实现方式:node,nginx,http-proxy-middleware,http-proxy等,本文主讲http-proxy-middleware和http-proxy这2中方式
1.http-proxy-middleware如何做反向地理
1.1安装依赖
npm i http-proxy-middleware
1.2http-proxy-middleware的常用api
const { createProxyMiddleware } = require("http-proxy-middleware")

const app = require("express")

const proxyArr = [
    {
        proxyPath: '/api',
        host: "http://localhost:6000"
    }
]

proxyArr.forEach(({ proxyPath, host }) => {
    app.use(proxyPath, createProxyMiddleware({
        target: host, //目标url
        ws: true, //是否改变原始主机头为目标url,默认为false
        changeOrigin: true, //是否允许跨域
        pathRewrite: { //重写路径
            ["^" + proxyPath]: proxyPath
        }
    }))
})

参考文档:https://github.com/chimurai/http-proxy-middleware

2.http-proxy详解
2.1安装http-proxy模块
npm i http-proxy
2.2http-proxy的api详解
const httpProxy = require("http-proxy"); //创建http-proxy实例
const http = require("http")

const server = httpProxy.createServer({})

http.createServer((req, res) => {
    server.web(req, res, { //代理http协议
        target: "http://localhost:4000",
        ws: false,
        ssl: { //如果target代理的是https,则要添加ssl配置项目,(https的公钥和私钥)
            key: "",
            cert: ""
        },
        secure: true //是否安全
    })

}).listen(3000)

server.web代理的是http和https
server.ws代理的websoket

//监听服务端请求数据
server.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); //设置请求头
});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值