You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Postman调用API无CORS问题,Web应用却出现CORS错误?

问题原因及解决方案

核心原因

  • 浏览器同源策略限制:Web页面所在域名与API域名(https://mat.cloud)不同,属于跨域请求,浏览器会自动触发CORS校验;而Postman作为非浏览器客户端,不受同源策略约束,因此能正常调用。
  • 你的API后端未返回CORS相关响应头,且带自定义请求头(x-api-key、Authorization)的GET请求会触发浏览器的预检OPTIONS请求,后端未处理该请求,导致浏览器判定跨域非法,抛出CORS错误。

解决方案(后端JAX-RS配置)

方法1:在API方法中添加CORS响应头

修改ClientService的getAll方法,在返回结果中补充CORS相关响应头:

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getAll() {
    List<TMmcClient> customer = customerDao.getAll();
    if (customer.isEmpty()) {
        throw new NotFoundException();
    }
    return Response.ok(customer, MediaType.APPLICATION_JSON)
            // 替换为你的Web页面实际域名,生产环境禁止用*
            .header("Access-Control-Allow-Origin", "http://你的前端域名:端口")
            // 允许前端携带的自定义请求头
            .header("Access-Control-Allow-Headers", "Content-Type, x-api-key, Authorization")
            // 允许的HTTP请求方法
            .header("Access-Control-Allow-Methods", "GET, OPTIONS")
            // 若需携带Cookie等凭证,设置为true
            .header("Access-Control-Allow-Credentials", "true")
            .build();       
}

方法2:全局CORS过滤器(推荐,统一处理所有API)

创建JAX-RS过滤器,统一拦截所有请求并添加CORS响应头,同时处理预检OPTIONS请求:

@Provider
public class CorsFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        // 生产环境替换为具体前端域名
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "http://你的前端域名:端口");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "Content-Type, x-api-key, Authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        
        // 直接响应预检OPTIONS请求,避免业务逻辑处理
        if (requestContext.getMethod().equals("OPTIONS")) {
            responseContext.setStatus(Response.Status.OK.getStatusCode());
        }
    }
}

内容的提问来源于stack exchange,提问作者pheromix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:05:56