我有jQuery AJAX调用Wordpress API,我需要在requestHeader中设置Nonce进行身份验证。
$.ajax({
url: '/wp-json/app/v1/get_data/',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', NONCE ); // NONCE is global var
},
data: {},
}).done(onSuccess);
然后我想将该代码转换为 Fetch API,所以我尝试了这个:
window.fetch('/wp-json/app/v1/get_data/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': NONCE
},
body: {},
}).then(onSuccess)
但是我得到 403 禁止,好像我的随机数没有被检测到。我不确定这是否是设置请求标头的正确方法。
我找不到太多关于 Fetch API 的信息,所以有人有这方面的经验吗?
谢谢
我通过在参数中添加credentials: 'same-origin'
来解决它
window.fetch('/wp-json/app/v1/get_data/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': NONCE
},
credentials: 'same-origin',
body: {},
}).then(onSuccess)
我现在让它工作了,上面的答案不起作用,我不得不串起身体数据
(async function fetchUsers(){
var datas = {
'title':'test'
}
const resOne = await fetch('http://localhost/elementor_barba/wp-json/wp/v2/posts/1',{
method : 'POST',
headers : {
'Content-Type': 'application/json',
'X-WP-Nonce' : universityData.nonce // here you used the wrong name
},
credentials: 'same-origin',
body:JSON.stringify(datas)
})
const dataOne = await resOne.json()
console.log(dataOne)
})()