如何通过配置 HTTP 代理解决跨域

1,234 阅读2分钟

HTTP 配置代理

本地开发过程中,因为本地启动前端项目时,一般使用 dev-server 较多,此时监听的服务地址通常是 localhost:xxxx, 这与接口服务所在地址就存在浏览器跨域问题。

虽然在接口所在的服务中,通过配置请求头的方式可以解决跨域,但是服务端不在我们手里,找后端太麻烦。

服务端配置请求头解决跨域

具体配置在响应中的内容如下所示:

Access-Control-Allow-Origin: "*";
Access-Control-Allow-Headers: "*";
Access-Control-Allow-Methods: "*"

在前端,我们可以通过配置HTTP代理的方式来解决跨域问题。

webpack-dev-server中配置代理

如果使用了 webpack 对前端资源进行打包,可以在 dev-server 配置中增加代理配置,如下所示:

//....
"/api": {
    target: "http://localhost:3000",
    bypass: function(req, res, proxyOptions) {
      if (req.headers.accept.indexOf("html") !== -1) {
        console.log("Skipping proxy for browser request.");
        return "/index.html";
      }
    }
  }
//....

express 中使用代理中间件

需要使用 http-proxy-middleware 中间件,进行代理配置。

npm i http-proxy-middleware

在 express 中使用的实例,

/**
 * Module dependencies.
 */
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

/**
 * 配置中间件
 */
const jsonPlaceholderProxy = createProxyMiddleware({
  target: 'http://jsonplaceholder.typicode.com',
  changeOrigin: true, // for vhosted sites, changes host header to match to target's host
  logLevel: 'debug',
});

const app = express();

/**
 * 使用中间件
 */
app.use('/users', jsonPlaceholderProxy);

app.listen(3000);

console.log('[DEMO] Server: listening on port 3000');
console.log('[DEMO] Opening: http://localhost:3000/users');

// 启动浏览器,并打开地址
require('open')('http://localhost:3000/users');

Koa2 使用代理中间件

koa2 中,可以使用 koa-server-http-proxy 中间件,此中间件是对 http-proxy-middleware 中间件按照 koa 中间的格式进行了简单封装,内部使用了 koa2-connect,实现和 express 类型的功能。

npm i koa-server-http-proxy

使用实例如下所示,

const Koa = require('koa')
const proxy = require('koa-server-http-proxy')

const app = new Koa()

app.use(proxy('/', {
	target: 'https://hub.fastgit.org',
	changeOrigin: true,
	pathRewrite: {
	 	'^/git': '/',
	 	'/search': '/'
	},
	hostRewrite: {
		// 'github.com': 'localhost:3000/'
	},
	secure: false,
}))

app.listen(3000);

// 访问 http://localhost:3000/ 查看效果

http-proxy 模块

无论是在 webpack-dev-serverexpress 或者是 koa 中,配置的 http 代理,底层使用的都是 http-proxy这个模块。

http-proxy 是一个功能强大的 HTTP 代理库,不但可以通过编程使用,还支持 websocket 协议。主要用于实现反向代理和负载均衡组件。

npm install http-proxy --save