Woocommerce API+React应用:GET正常,POST/PUT请求401未授权失败
解决WooCommerce + React POST请求401未授权问题
检查API密钥权限
- 确认你使用的WooCommerce API密钥(Consumer Key和Consumer Secret)开启了写权限。创建密钥时,权限需选择"Read/Write",而非只读。
- 操作路径:WordPress后台 → WooCommerce → 设置 → 高级 → REST API → 编辑对应密钥,检查权限设置。
验证请求签名与参数
- POST请求必须正确携带验证信息,不能仅在GET请求中配置。若使用Basic Auth,需确保请求头里的
Authorization格式正确:Basic base64(ConsumerKey:ConsumerSecret) - 务必设置POST请求的
Content-Type: application/json,否则WooCommerce API无法解析请求体,会直接导致授权验证失败。 - React请求示例代码:
const consumerKey = '你的Consumer Key'; const consumerSecret = '你的Consumer Secret'; const auth = btoa(`${consumerKey}:${consumerSecret}`); fetch('http://localhost/wordpress/wp-json/wc/v3/products', { method: 'POST', headers: { 'Authorization': `Basic ${auth}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '测试产品', type: 'simple', regular_price: '19.99' }) }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
本地环境跨域问题
- 尽管GET请求正常,但POST可能触发更严格的CORS检查。可在本地WordPress中安装激活WP CORS插件,或在主题的
functions.php中添加以下代码允许跨域:
add_action('init', 'allow_cors'); function allow_cors() { header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Authorization, Content-Type"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; } }
- 注意:本地开发用
*即可,生产环境需替换为你的React域名。
排查安全插件拦截
- 若安装了Wordfence、iThemes Security这类安全插件,它们可能拦截POST请求。可暂时禁用这类插件测试,确认是否是插件导致的授权拦截。
验证HTTP/HTTPS一致性
- 本地XAMPP使用HTTP协议,需确保React请求的URL以
http://开头,与WordPress站点地址完全一致,避免混用HTTPS(比如React用localhost:3000,WordPress用http://localhost/wordpress)。
内容的提问来源于stack exchange,提问作者daniel muñoz
相关产品推荐
相关产品推荐

