如何修复Axios中的CORS multiple origin not allowed错误(WordPress API后端)
解决Axios调用WordPress API时的CORS多源不允许错误
用Axios发起GET请求获取WordPress API数据时,遇到了CORS multiple origin not allowed错误,后端返回的响应头如下:
HTTP/1.1 200 OK Server: nginx Date: Wed, 29 Mar 2023 10:48:56 GMT Content-Type: application/json; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive Access-Control-Allow-Origin: * X-Robots-Tag: noindex Link: <https://devapi.markazeahan.com/rest/>; rel="https://api.w.org/" X-Content-Type-Options: nosniff Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages, Link, Link Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type Allow: GET Access-Control-Allow-Methods: GET Access-Control-Allow-Credentials: true Cache-Control: max-age=0 Expires: Wed, 29 Mar 2023 10:48:55 GMT Vary: Accept-Encoding Access-Control-Allow-Origin: *
问题原因
- 重复的CORS响应头:响应头里
Access-Control-Allow-Origin: *出现了两次,浏览器会因为重复的同源允许字段抛出错误。 - 凭证与通配符冲突:当设置
Access-Control-Allow-Credentials: true时,Access-Control-Allow-Origin不能用通配符*,必须指定具体域名,这两个配置同时存在会触发CORS规则冲突。
解决方案
- 移除重复的响应头:检查WordPress的CORS配置(插件或自定义代码),确保只输出一次
Access-Control-Allow-Origin字段。 - 调整Origin与Credentials配置:
- 如果前端请求需要携带凭证(如Cookie),将
Access-Control-Allow-Origin设置为前端的具体域名(如https://your-frontend.com),保留Access-Control-Allow-Credentials: true。 - 如果不需要带凭证,删除
Access-Control-Allow-Credentials: true,继续使用*作为允许源。
- 如果前端请求需要携带凭证(如Cookie),将
- WordPress代码配置示例:在主题的
functions.php中添加以下代码,精准控制CORS头:
add_action('rest_api_init', function () { remove_filter('rest_pre_serve_request', 'rest_send_cors_headers'); add_filter('rest_pre_serve_request', function ($value) { $origin = get_http_origin(); if ($origin) { // 替换为你的前端允许域名列表 $allowed_origins = [ 'https://your-frontend-domain.com', 'http://localhost:3000' ]; if (in_array($origin, $allowed_origins)) { header("Access-Control-Allow-Origin: $origin"); } } header('Access-Control-Allow-Methods: GET'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type'); return $value; }); });
- 前端Axios适配:若后端开启了凭证支持,请求时需添加
withCredentials: true:
axios.get('https://devapi.markazeahan.com/rest/your-api-endpoint', { withCredentials: true }) .then(res => { // 处理返回数据 }) .catch(err => { console.error(err); });
内容的提问来源于stack exchange,提问作者Alireza Bagheri
相关产品推荐
相关产品推荐

