在这里强烈建议每个人通读一下 MDN 的HTTP 访问控制 ,这篇图文并茂的文章可以解决跨域百分之八十的疑惑。
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/, '')
}
}
},})
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 "你的项目地址";
}
}
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-Origin
、Access-Control-Allow-Headers
、Access-Control-Allow-Methods
头的相应设置。