Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 试图将jQueryAjax转换为FetchAPI,如何设置RequestHeader?_Javascript_Jquery_Ajax_Wordpress_Fetch - Fatal编程技术网

Javascript 试图将jQueryAjax转换为FetchAPI,如何设置RequestHeader?

Javascript 试图将jQueryAjax转换为FetchAPI,如何设置RequestHeader?,javascript,jquery,ajax,wordpress,fetch,Javascript,Jquery,Ajax,Wordpress,Fetch,我有对Wordpress API的jQuery AJAX调用,我需要在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: {}, }

我有对Wordpress API的jQuery AJAX调用,我需要在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);
然后我想将该代码转换为获取API,因此我尝试了以下方法:

window.fetch('/wp-json/app/v1/get_data/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': NONCE
  },
  body: {},
}).then(onSuccess)
但我得到了403禁止,就好像我的Nonce没有被检测到一样。我不确定设置requestHeader是否正确

我找不到关于FetchAPI的太多信息,所以有人有这方面的经验吗


谢谢

我通过在参数中添加
凭据:“同源”
解决了这个问题

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)
})()