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

从本地主机访问WordPress REST API时出现CORS错误

本地主机访问WordPress REST API跨域问题排查

问题详情

从http://localhost访问远程WordPress REST API时触发CORS错误,请求代码如下:

$.ajax({
  url: "https://example.com/wp-json/wp/v2",
  success: function (result) {
    console.log(result);
  },
  error: function (error) {
    console.log(error);
  }
});

错误提示:

Access to XMLHttpRequest at 'https://example.com/wp-json/wp/v2' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

同源环境下请求正常,但已在Storefront主题的functions.php中添加以下代码仍未解决问题:

header( 'Access-Control-Allow-Origin: *'  );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );

排查与解决步骤

  1. 修正WordPress头部添加方式
    直接在functions.php顶部写入header()会被WordPress默认的头部机制覆盖,需通过rest_api_init钩子添加:
add_action( 'rest_api_init', function() {
  remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  add_filter( 'rest_pre_serve_request', function( $value ) {
    header( 'Access-Control-Allow-Origin: http://localhost' ); // 避免用*,和Credentials冲突
    header( 'Access-Control-Allow-Methods: GET, OPTIONS' );
    header( 'Access-Control-Allow-Credentials: true' );
    return $value;
  } );
}, 15 );

注意:Access-Control-Allow-Origin: *与Access-Control-Allow-Credentials: true不能同时使用,这是CORS规则的硬性要求。

  1. 清空缓存与CDN
    如果站点使用了缓存插件(如WP Rocket)或CDN服务(如Cloudflare),旧的响应头部可能被缓存,需清空所有缓存后再测试。

  2. 直接配置服务器

  • Apache服务器:在站点根目录的.htaccess中添加规则(优先级高于主题代码):
<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "http://localhost"
  Header set Access-Control-Allow-Methods "GET, OPTIONS"
  Header set Access-Control-Allow-Credentials "true"
</IfModule>
  • Nginx服务器:在站点配置的server块中添加:
location ~ ^/wp-json/ {
  add_header Access-Control-Allow-Origin http://localhost;
  add_header Access-Control-Allow-Methods GET,OPTIONS;
  add_header Access-Control-Allow-Credentials true;
}

修改后重启服务器生效。

  1. 使用专用CORS插件
    安装WordPress官方生态的CORS管理插件(如WP CORS),这类插件会自动适配REST API的跨域规则,无需手动编写代码。

  2. 处理预检请求
    浏览器跨域请求前会发送OPTIONS预检请求,需确保服务器未拦截该请求,上述配置已包含对OPTIONS方法的支持,可通过开发者工具的网络面板检查OPTIONS请求的响应头部是否正确。

内容的提问来源于stack exchange,提问作者Md Mobinur Rahaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:15:42