javascript - 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' ); ?>"
非常感谢!:)
解决方案
推荐阅读
- java - Android 扩展 MainActivity
- android-studio - 迁移到 AndroidX 后的 Lint 错误:
- reactjs - 创建一个 React .JSX React 组件
- c# - WPF中的滚动条
- xcode - iOS 版本未显示在 appstoreconnect 中
- angularjs - Chrome 的调试器:无法使用附加选项进行调试
- sql - 在 Presto 中拆分并返回除第一个元素之外的所有元素
- python - 使用 SSL 的 manage.py runserver 0:8000
- powerbi - Power BI Desktop 中传入订单和已完成订单的比较
- python - 分类已经找到中心的字符串,python