IIS 设置代理实现前端跨域请求后端接口

IIS10 前端服务器,设置代理实现跨域请求后端接口

摘要

本文介绍 IIS10 通过安装 ARR 3.0(Application Request Routing),配置 Application Request Routing Cache 开启代理,配置 URL Rewrite 创建匹配规则,实现前端跨域请求 API 功能。即访问 http://localhost:8001/api/list,实际会被代理到 http://localhost:8002/api/list 。

## 原请求
http://localhost:8001/api/list   

## 实际代理到后端服务
http://localhost:8002/api/list

服务器环境

IIS 前端服务器

IIS 服务器创建一个端口为 8001 的网站,目录下有一个 test.html,请求接口地址为 "/api/get.json" 。访问地址为:http://localhost:8001/test.html 。

Node.js 后端服务器

使用 http-server 开启一个端口为 8002 的服务器,"api"目录下一个 JSON 文件 get.json ,访问地址为:http://localhost:8002/api/get.json 。

一. 安装 ARR 3.0(Application Request Routing)

访问 IIS 官方网站:https://www.iis.net/downloads/microsoft/application-request-routing ,有两种安装方式。

  • 通过 Web 平台安装程序(Web Platform Installer):直接点击 “Install this extension” 按钮即可。
  • 下载包安装:x86 installer / x64 installer 。
# 重启 IIS
iisreset

二. 配置 Application Request Routing Cache

1、安装成功后,IIS 管理里会看到多出一个图标 "Application Request Routing Cache",点击进去进行配置。

001.jpg

2、进去后,点击 Server Proxy Settings

002.jpg

3、在设置页面,勾选 Enable proxy, 。

003.jpg

4、应用保存刚才设置。

三. 配置 URL 重写(URL Rewrite)

1、进入 IIS 网站管理,可以看到多出一个 URL 重写(URL Rewrite) 的图标。

004.jpg

2、进入 URL 重写(URL Rewrite),点击“添加规则”。

005.jpg

3、进入添加规则弹窗,点击“空白规则”。

006.jpg

4、配置规则:

# 模式(T)
^(.*?)/?api/(.*)$

# 重写 URL(L)
http://localhost:8002/{R:0}  
007.jpg

即 8001 端口的前端服务器,访问路径中包括 /api/ 的请求,会被代理到 8002 端口的后端服务器。

5、应用保存配置。

测试

访问前端服务器:http://localhost:8001/test.html ,可以看到接口访问地址(http://localhost:8001/api/get.json) 状态码是 502

test-001.jpg

这是因为还没开启后端服务器,让我们开启再试一下。

test-002.jpg

现在刷新前端页面(http://localhost:8001/test.html),可以看到接口请求已经成功。

test-003.jpg

再回到后端服务器,查看日志,可以看到刚才有一条 GET 请求记录,证明刚才 8001 端口服务器的请求,已经成功代理到 8002 端口服务器的了。

test-004.jpg

结语

IIS 配置偏图形化,按理讲应该更友好一些,但事实是增添了很多操作步骤,比起Nginx 的几行配置文件,实际体验反而复杂许多。

参考资料

  • https://docs.microsoft.com/en-us/iis/extensions/configuring-application-request-routing-arr/creating-a-forward-proxy-using-application-request-routing
  • https://www.iis.net/downloads/microsoft/application-request-routing
  • https://www.cnblogs.com/yuzhihui/p/9335035.html

【无稽山】原创作品(公众号:无稽山)

你可能感兴趣的:(IIS 设置代理实现前端跨域请求后端接口)