首页 > 解决方案 > jQuery ajax 基本身份验证仅适用于外部网站,但不适用于本地请求

问题描述

此代码在外部网站(例如 jsfiddle.net)上使用时有效

但不是在我的网站本身上使用时:

var $ = jQuery;

var makeBaseAuth = function(user, pswd){ 
    var token = user + ":" + pswd;
    var hash = "";
    if (btoa) {
        hash = btoa(token);
    }
    return "Basic " + hash;
};

var settings = {
    "crossDomain": true,
    "url": "http://mywebsite.org/wp-json/wp/v2/settings",
    "method": "GET",
    "headers": {
        "authorization": makeBaseAuth("admin", "mypassword")
    }
}

$.ajax(settings)
.done(function(response){
    console.log(response);
})
.error(function(err){
    console.log(err);
});

我收到这个错误

responseText: "{"code":"rest_forbidden","message":"你没有权限这样做。","data":{"status":401}}"

statusText:“未授权”

我尝试使用"crossDomain": false但没有成功...

为什么它不起作用?我怎样才能使它也可以从本地请求中工作?


更新:感谢您的建议,我通过添加此标题解决了:

"X-WP-NONCE": "<?php echo wp_create_nonce( 'wp_rest' ); ?>"

非常感谢!:)

标签: javascriptjqueryajaxauthorization

解决方案


推荐阅读