WordPress REST API 是现代WordPress开发中不可或缺的功能,它允许开发者通过HTTP请求与WordPress站点进行数据交互。然而在实际开发中,特别是前端应用与WordPress后端分离部署时,经常会遇到跨域资源共享(CORS)问题。
什么是跨域问题
跨域问题源于浏览器的同源策略(Same-Origin Policy),当你的前端应用(如React/Vue)运行在http://localhost:3000
,而WordPress站点部署在http://example.com
时,浏览器会阻止这种跨域请求。
WordPress REST API跨域解决方案
1. 修改WordPress主题的functions.php
最直接的方法是在当前主题的functions.php
文件中添加以下代码:
function add_cors_http_header() {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
}
add_action('init', 'add_cors_http_header');
2. 使用CORS插件
对于不熟悉代码修改的用户,可以安装专门的CORS插件:
- WP CORS:简单易用的跨域支持插件
- JWT Authentication for WP REST API:同时提供JWT认证和CORS支持
3. Nginx服务器配置
如果你的WordPress运行在Nginx服务器上,可以在站点配置中添加:
location /wp-json/ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
}
4. Apache服务器配置
对于Apache服务器,可以在.htaccess
文件中添加:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, PUT, DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
安全注意事项
- 生产环境中不建议使用
Access-Control-Allow-Origin: *
,应该指定具体的域名 - 对于需要认证的API端点,确保只对可信来源开放跨域访问
- 考虑结合JWT等认证机制保护API安全
测试跨域是否生效
可以使用以下JavaScript代码测试跨域是否配置成功:
fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
通过以上方法,你可以轻松解决WordPress REST API的跨域问题,为前后端分离开发扫清障碍。