跨域访问方法介绍(9)--nginx 反向代理
Nginx (engine x) 是一个高性能的HTTP 和反向代理web服务器,同时也提供了 IMAP/POP3/SMTP 服务。本文主要介绍使用 Nginx 反向代理来实现跨域请求,文中所使用到的软件版本:Nginx 1.21.0、Spring Boot 2.4.4、jdk1.8.0_181。
1、思路
在前后端分离的项目里,可以把前端项目部到 Nginx 里面,通过 Ajax 访问后台接口。如果通过 Ajax 直接访问后端接口会形成跨域请求,如果不能或不想使用 JSONP 或 CORS 来解决跨域问题,可以使用 Nginx 的反向代理来解决跨域问题。Ajax 不直接请求后端接口,而是请求 Nginx 的一个 URL,该 URL 配置反向代理到后端服务。
2、样例
在 http://localhost:8080/a.html 中 访问 http://localhost:8081/test/getStudents 接口。
2.1、后台 Contoller
package com.abc.demo.controller; import com.abc.demo.entity.R; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RequestMapping("/test") @Controller public class TestController { @ResponseBody @RequestMapping("/getStudents") public R<List<Map<String, String>>> getStudents() { List<Map<String, String>> result = new ArrayList<>(); Map<String, String> map = new HashMap<>(); map.put("name", "李白"); map.put("age", "20"); result.add(map); map = new HashMap<>(); map.put("name", "杜甫"); map.put("age", "21"); result.add(map); return R.ok(result); } }
2.2、Nginx 配置
server { listen 8080; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } location /test { proxy_pass http://localhost:8081/test; } ...
2.3、页面(a.html)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body> </body> <script type="text/javascript" src="./jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function(){ $.ajax({ url: 'http://localhost:8080/test/getStudents', //如果这里设为http://localhost:8081/test/getStudents,会报跨域错误 type: 'post', dataType: 'json', contentType: 'application/json', data: { }, success: function(resp) { alert(JSON.stringify(resp)); } }); }); </script> </html>
2.4、测试
把 a.html 放到 Nginx(端口:8080) 的 html 目录下,驱动后端 SpringBoot(端口:8081) 应用。