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

配置Nginx的server_name后Fetch API失效,报错net::ERR_BLOCKED_BY_CLIENT

问题排查与解决方案

1. 先修正Nginx后端配置的致命拼写错误

你后端Nginx配置里的proxy_pass http://ocalhost:7778/;存在拼写错误:ocalhost少了字母l,应该改为localhost。这个错误会导致Nginx无法正确代理请求到后端服务,是引发错误的核心原因之一。

修正后的后端Nginx配置:

server {
    listen 80;
    server_name api.localhost;

    location /first-api/ {
        proxy_pass http://localhost:7777/;
    }

    location /second-api/ {
        proxy_pass http://localhost:7778/;
    }
}

修改后重启Nginx服务。

2. 排查客户端拦截因素

net::ERR_BLOCKED_BY_CLIENT错误大多来自客户端层面的拦截:

  • 关闭浏览器的广告拦截扩展(如AdBlock、uBlock Origin),这类工具可能会拦截localhost域名下的请求
  • 切换到浏览器无痕模式测试,排除扩展插件的干扰

3. 确认本地Hosts文件配置

确保本地Hosts文件中已添加以下解析规则,否则home.localhost和api.localhost无法指向本地服务:

127.0.0.1 home.localhost
127.0.0.1 api.localhost

4. 优化CORS配置(避免冲突)

虽然你已经在Express和Nginx中配置了CORS,但重复设置可能导致响应头冲突,建议保留其中一处即可。如果选择用Nginx统一处理CORS,可以在后端Nginx的server块中添加以下配置:

add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header Access-Control-Expose-Headers 'Content-Length,Content-Range';

# 处理OPTIONS预检请求
if ($request_method = 'OPTIONS') {
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header Access-Control-Max-Age 1728000;
    add_header Content-Type 'text/plain; charset=utf-8';
    add_header Content-Length 0;
    return 204;
}

同时可以移除Express中的cors配置,避免头信息重复。

5. 验证接口路径匹配

确保前端Fetch请求的路径与Nginx代理规则匹配:
比如前端需要请求http://api.localhost/second-api/v1/greetings,才能被Nginx代理到http://localhost:7778/v1/greetings,路径不匹配会导致404,进而可能触发客户端拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:30:13