TypechoJoeTheme

香草物语

统计
登录
用户名
密码
/
注册
用户名
邮箱
输入密码
确认密码

Spring Boot 配合nginx完成跨域配置

Laughing博主
2020-09-28
/
0 评论
/
1,639 阅读
/
433 个字
/
百度已收录
09/28
本文最后更新于2024年03月18日,已超过185天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!

springboot配置跨域 我们介绍了spring boot两种配置跨域的方式。


实际项目中,我用的一般是通过nginx进行跨域设置。

nginx跨域实现的几个目标

  1. 肯定是能正常跨域访问
  2. 为了方便跨域,我们一般对后台api进行封装,统一返回一个前缀作为区分

    我们先来实现第二个目标,统一后端返回的api地址。

    方法一、通过yaml配置

    通过配置文件设置

    server:
      servlet:
     context-path: /api

    这样,我们在前端的请求,都会自动加上'/api'前缀。但是这样的设置存在两个问题:

  3. 所有的请求全部都是'/api'前缀。
  4. 静态资源要求带'/api'前缀。
    所以,我们需要通过更优雅的方式来进行设置,也就是方法二。

    方法二、通过实现WebMvcConfigurer接口的configurePathMatch方法

    首先我们在配置文件,增加自定义的前缀

    #配置api前缀
    request-path:
      api-path: /api

    注入配置信息

    /**
     * @author laughing
     * @date 2020/9/26
     * @site https://www.xiangcaowuyu.net
     */
    @Configuration
    @ConfigurationProperties(prefix = "request-path")
    @Data
    public class RequestPathProperties {
    
     private String apiPath;
    
    }

    增加自定义注解

    /**
     * @author laughing
     * @date 2020/9/26
     * @site https://www.xiangcaowuyu.net
     */
    @RestController
    @Target({ElementType.TYPE})
    @Documented
    @RequestMapping
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ApiRestController {
    
     /**
      * Alias for {@link RequestMapping#name}.
      */
     @AliasFor(annotation = RequestMapping.class)
     String name() default "";
    
     /**
      * Alias for {@link RequestMapping#value}.
      */
     @AliasFor(annotation = RequestMapping.class)
     String[] value() default {};
    
     /**
      * Alias for {@link RequestMapping#path}.
      */
     @AliasFor(annotation = RequestMapping.class)
     String[] path() default {};
    
    }

增加实现WebMvcConfigurer的configurePathMatch方法,配置前缀

/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Resource
    RequestPathProperties requestPathProperties;

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(requestPathProperties.getApiPath(), c->c.isAnnotationPresent(ApiRestController.class));
    }
}

经过如上配置,我们所有注解@ApiRestController的请求,都会增加'/api'前缀
增加两个配置类,一个通过@ApiRestController注解,一个通过普通的@RestController注解,分别访问测试

/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@ApiRestController
public class NginxCorsController {

    @RequestMapping("/nginxCors")
    public String nginxCors(){
        return "nginxCors";
    }

}
/**
 * @author laughing
 * @date 2020/9/26
 * @site https://www.xiangcaowuyu.net
 */
@RestController
public class NormalController {

    @RequestMapping("/normal")
    public String normal(){
        return "normal";
    }

}

支持,完成了spring boot后台统一api地址的目标

nginx配置跨域

前端代码

我们先配置前端页面,发起一个简单的post请求

<!DOCTYPE html>
<html>

<head>
    <title>Welcome to nginx!</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>
    <div id="myDiv"></div>
    <script>
        $(document).ready(function () {

           $.ajax({
                url: "/api/nginxCors",
                type:"post",
                async: false,
                success:function(data){
                    $("#myDiv").html(data);
                }
            });
           

        });
    </script>
</body>

</html>

nginx配置

我们要配置的规则很简单,所有/api开头的请求,全部重定向到后端spring boot上。

  1. 打开nginx配置文件,我这里使用的是默认的,及'nginx.conf'
  2. 修改location

    server {
         listen       1234;
         server_name  localhost;
    
         #charset koi8-r;
    
         #access_log  logs/host.access.log  main;
    
         #简单配置跨域
         location /api {
             proxy_pass http://localhost:8080/api/;
         }
         
         location / {
             root   html;
             index  index.html index.htm;
         }
    
         #error_page  404              /404.html;
    
         # redirect server error pages to the static page /50x.html
         #
         error_page   500 502 503 504  /50x.html;
         location = /50x.html {
             root   html;
         }
    
         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
         #
         #location ~ \.php$ {
         #    proxy_pass   http://127.0.0.1;
         #}
    
         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
         #
         #location ~ \.php$ {
         #    root           html;
         #    fastcgi_pass   127.0.0.1:9000;
         #    fastcgi_index  index.php;
         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
         #    include        fastcgi_params;
         #}
    
         # deny access to .htaccess files, if Apache's document root
         # concurs with nginx's one
         #
         #location ~ /\.ht {
         #    deny  all;
         #}
     }
  3. 重新加载nginx配置文件
    这里用的win,linux需要对应替换命令

    nginx.exe -s reload

    打开页面测试,可以看到能够正常跨域

NginxSpring Boot
朗读
赞(0)
赞赏
感谢您的支持,我会继续努力哒!
版权属于:

香草物语

评论 (0)
  1. 闲逛
    Windows 10 · Google Chrome

    麻烦通过下,测试下这个能不能用

    2018-09-20 回复
  2. 逍遥浪子 小坐
    Windows 10 · MicroSoft Edge

    怎么样才能显示密码或得到密码呢

    2018-05-21 回复