用Nginx代理请求,处理前后端跨域

  自从前端spa框架出现后,都是前后端分离开发了。我们在开发的时候难免会遇到跨域的问题。跨域这种问题解决的方法基本都是在服务端实现的。以java为例,我知道的有3种方法处理跨域:

  1.使用 @CrossOrigin 注解对每一个接口进行跨域处理,缺点是比较麻烦

@CrossOrigin(origins ="*")
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
    return "test";
}

  2.使用 @CrossOrigin 在入口类对所有接口进行跨域处理

@CrossOrigin(origins = "*")
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
    // ***
}

  3.还可以添加一个配置类,对所有的接口进行跨域处理

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

  但是...我们项目组的后端他们不在代码中处理跨域,通过线上的nginx统一配置跨域处理...我们前端用的vue,vue配置中是有对于开发跨域的处理,由于我们项目的特殊性,并不适合我们(我们一套代码会运行会部署在不同的服务器,至少3套,前后端代码有差异,我们通过gitlab分支解决代理管理,我们将差异抽离出来成为不同版本代码的配置,例如不同的后台api接口地址,刚开始我们前端代码在构建的时候将配置打进去,发现这样还是代码和配置傻傻分不清楚,这样子处理的不是很好,我们为了前端代码和配置的彻底分离,将代码和配置分别建立两个gitlab仓库,前端项目构建的时候只是构建代码,配置会在部署的时候通过脚本对特定环境进行替换,我感觉跟猴子补丁有点类似,以此来达到跟后台java一样一套代码,运行时用不同命令读取不同的配置运行)本着自己散装的nignx配置了解,可以通过本地nginx做一个请求代理转发,然后在nginx中处理跨域

server {
    listen 9090;
    server_name localhost;

    location /{
        add_header ‘Access-Control-Allow-Origin‘ $http_origin;
        add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
        add_header ‘Access-Control-Allow-Headers‘ ‘*‘;

        if ($request_method = "OPTIONS") {
            add_header ‘Access-Control-Allow-Origin‘ $http_origin;
            add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
            add_header ‘Access-Control-Allow-Headers‘ ‘*‘;
            add_header ‘Content-Length‘ 0;
            add_header ‘Content-Type‘ ‘text/plain, charset=utf-8‘;
            return 204;
        }

        proxy_pass http://192.168.0.3:9999;
    }

    #location /aepreservation {
    #
    #    add_header ‘Access-Control-Allow-Origin‘ $http_origin;
    #    add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
    #    add_header ‘Access-Control-Allow-Headers‘ ‘*‘;

    #    if ($request_method = "OPTIONS") {
    #        add_header ‘Access-Control-Allow-Origin‘ $http_origin;
    #        add_header ‘Access-Control-Allow-Methods‘ ‘GET, POST, OPTIONS‘;
    #        add_header ‘Access-Control-Allow-Headers‘ ‘*‘;
    #        add_header ‘Content-Length‘ 0;
    #        add_header ‘Content-Type‘ ‘text/plain, charset=utf-8‘;
    #        return 204;
    #    }

    #   proxy_http_version 1.1;
    #   proxy_set_header Upgrade $http_upgrade;
    #   proxy_set_header Connection "upgrade";
    #    proxy_pass http://192.168.0.3:9999;
   #}
}

  nginx监听本地端口9090的所有端口,并转发到对应的后端服务(假如你们后台服务的地址为 http://192.168.0.3:9999/api/*,我们的前端代理只要访问 http:localhost:9090/api/*就可以了,注意下方我注释的地方是代理websocket的方法,路径是/aepreservation,我当时为了偷懒(正则看着头疼),抄了一份上边的配置,ningx是可以通过正则判断的,只对确定的websocket路径进行处理,不用向我一样写的这么啰嗦

原文地址:https://www.cnblogs.com/hanshuai/p/11128472.html

时间: 2024-08-02 23:41:23

用Nginx代理请求,处理前后端跨域的相关文章

简单设置,解决使用webpack前后端跨域发送cookie的问题

最近用vue来做项目,用webpack来做前端自动化构建.webpack-dev-server会在本地搭建一个服务器,在和后端调试的时候,就会涉及到跨域的问题. 刚开始时,没有用vue-cli来构建项目,而是参考了github上的vue-vueRouter-webpack来构建.看网上的资料,vue-cli可以通过配置代理来解决跨域的问题: proxyTable: { '/list': { target: 'http://api.xxxxxxxx.com', changeOrigin: true

cors跨域资源共享---解决前后端跨域问题

Cross-Origin Resource Sharing (CORS) ,定义了在跨域访问资源时浏览器和服务器之间如何通信.CORS背后的基本思想是使用自定义的HTTP头部允许浏览器和服务器相互了解对方,从而决定请求或响应成功与否. 解决方法: ①后端加响应头 header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Credentials: true'); header('Access-Contro

java 前后端跨域问题解决

前端页面部署在nginx 上 ,后端代码部署在服务器上 ,前端访问后台会出现跨域问题 新建一个过滤器 /** * 开放跨域权限 * * */@Slf4jpublic class testFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest var1, ServletResponse

springboot 解决前后端跨域

项目web层创建文件夹名字随便 和controller平级 在文件夹下创建类 名字随意  我是在tools文件夹下创建了一个叫CorsConfig的类,代码如下 package com.huyuqiang.web.tools; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframew

springboot2.1.3 配置前后端跨域问题

很简单,创建一个配置类即可,如下: package com.app.gateway.common.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebM

nginx 配置add_header 'Access-Control-Allow-Origin' '*' 依然存在跨域问题

.问题描述:前端域名A 在POST请求后端域名为B 的一个接口时候请求成功时不存在跨域问题,请求失败时浏览器提示跨域. 解决:当请求成功时,HTTP CODE 为200.而请求失败时HTTP CODE 为400, 此时add_header ‘Access-Control-Allow-Origin’ ‘*’ 配置无效!设置无论HTTP CODE 为何值时都生效需要加 always .nginx版本>1.7.5时候无须加always. add_header 'Access-Control-Allow

CORS跨域请求:前后端分离

请求过滤器: /** * OncePerRequestFilter保证在任何Servlet容器中都是一个请求只执行一次的过滤器. */ public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletEx

nginx 代理请求导出功能bug解决方法

问题描述: nginx代理的ip直接访问可以直接下载文件,但是通过nginx访问就报502,nginx错误日志:upstream sent invalid chunked response while reading upstream(在上游读取时发送了无效的分块响应): 解决办法: 在nginx配置的location下添加如下两行代码: proxy_http_version 1.1; proxy_set_header Connection ""; 还有个很坑的问题是测试环境配置了两个

Nodejs代理解决开发环境下跨域问题

前后端分离的项目,需要解决开发环境下跨域的问题: 转载链接:https://www.cnblogs.com/ytu2010dt/p/5959899.html 1.安装node环境 2.新建JS文件:nodeProxy.js 代码: "use strict"; const express = require('express'); const path = require('path'); const app = express(); const request = require('r