【CORS】前端、后端 跨域配置

2023-04-27 15:16:06 浏览数 (1)

1. 前言

在这里强烈建议每个人通读一下 MDN 的HTTP 访问控制 ,这篇图文并茂的文章可以解决跨域百分之八十的疑惑。

2. 前端配置

2.1 vite 中配置

代码语言:javascript复制
export default defineConfig({
server: {
		cors: true,// 允许跨域
		proxy: {
			'/api': {
				target: '后端服务地址',
				changeOrigin: true,
				ws: true, // 允许websocket代理
				// rewrite: ( path ) => path.replace(new RegExp('^/api'), '')
				rewrite: (path) => path.replace(/^/api/, '')
			}
		}
	},})

3. 后端配置

3.1 Nginx

代码语言:javascript复制
location ^~ /api {
  proxy_set_header Origin '';
  add_header Access-Control-Allow-Credentials true;
  add_header Access-Control-Allow-Headers $http_access_control_request_headers;
  add_header Access-Control-Allow-Methods POST,GET,OPTIONS,DELETE,PUT,HEAD,PATCH;
  add_header Access-Control-Allow-Origin $http_origin;
  add_header Access-Control-Expose-Headers $http_access_control_request_headers;

  if ($request_method = 'OPTIONS') {
    return 204;
  }
  if ($request_method != 'OPTIONS'){
    proxy_pass "你的项目地址";
  }
}

3.2 Java

代码语言:javascript复制
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpErrorResponseUtil {
    public static void setResponeCorsHeader(HttpServletRequest request, HttpServletResponse response) {
      response.addHeader("Access-Control-Allow-Credentials", "true");
      response.addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT,HEAD,PATCH");
      response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      response.addHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
    }
}

在别的语言中方法也大同小异,最重要的是 Access-Control-Allow-OriginAccess-Control-Allow-HeadersAccess-Control-Allow-Methods 头的相应设置。

0 人点赞