专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Nginx的跨域配置

使用SpringBoot开发前后端分离的应用,可以使用Nginx作为网关来统一解决跨域问题。这种好处是,可以不修改应用代码的情况下,让应用支持跨域。

对于很多不支持的跨域的网站,你也可以弄个Nginx给它“加个Buff”,也就可以进行跨域访问了。 :laughing:

Nginx配置(这个配置,可以解决 95% 以上的跨域问题)

server {
    listen 80;
    server_name localhost 127.0.0.1;
    location / {
        # 允许跨域请求的“域”
        add_header 'Access-Control-Allow-Origin' $http_origin;
        # 允许客户端提交Cookie
        add_header 'Access-Control-Allow-Credentials' 'true';
        # 允许客户端的请求方法
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
        # 允许客户端提交的的请求头
        add_header 'Access-Control-Allow-Headers' 'Origin, x-requested-with, Content-Type, Accept, Authorization';
        # 允许客户端访问的响应头
        add_header 'Access-Control-Expose-Headers' 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma';
        # 处理预检请求
        if ($request_method = 'OPTIONS') {
            # 预检请求缓存时间
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        # SpringBoot 应用访问路径
        proxy_pass http://127.0.0.1:8080;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 600;
        proxy_read_timeout 600;
    }
}

关于Nginx的下载,配置,启动等这些杂七杂八的东西,这里不多赘述,如果你还没接触过Nginx,现在就是个好机会,Nginx官网

SpringBoot Controller

// 在 8080 端口 提供服务
@RequestMapping("/test")
@RestController
public class TestController {

    @GetMapping("/cors")
    public Object corsTest () {
        return Collections.singletonMap("name", "SpringBoot中文社区");
    }
}

测试

浏览器新开一个页面就可以进行测试,主要能执行js。跨域嘛,只要是端口,url,协议。任意不同就可以了。

跨域失败

直接请求SpringBoot服务(8080端口),跨域失败。

35_1.png

跨域成功

请求Nginx网关服务(80端口),跨域成功

35_2.png

springboot.io/t/topic/221…

文章永久链接:https://tech.souyunku.com/35532

未经允许不得转载:搜云库技术团队 » Nginx的跨域配置

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们