使用JavaScript向Yesmail发出GET请求

时间:2018-07-24 00:26:34

标签: javascript fetch-api get-request

我正在尝试向Yesmail API发出GET请求,并根据消息ID返回与电子邮件营销活动相关联的数据,该消息ID目前已被硬编码,但最终会被传递。现在,我不断收到401(未经身份验证)。我一直在使用“ Sample Request Header”,但仍然缺少一些东西。我是否正确构造标题?我是否完全传递了正确的参数?

function doFetch(ev) {
  // this needs to be HTTPS
  let uri = 'https://api.test.yesmail.com/v2/reports/master-events/message_id_here';

  let h = new Headers();
  let encoded = window.btoa('my_key_here');
  h.append('Accept', 'application/json');
  h.append('Api-key', 'encoded');
  h.append('Api-User', 'my_username_here');
  h.append('Content-Type', 'application/json; charset=utf-8');
  h.append('Connection', 'keep-alive');

  let req = new Request(uri, {
    method: 'GET',
    headers: h,
    mode: 'cors'
  });
  // credentials: 'include' means a different domain.
  // credentials: 'same-origin' means the same domain.

  fetch(req)
  .then( (response)=>{
      if(response.ok){
          return response.json();
      }else{
          throw new Error('BAD HTTP stuff');
      }
  })
  .then( (jsonData) =>{
      console.log(jsonData);
      p.textContent = JSON.stringify(jsonData, null, 4);
  })
  .catch( (err) =>{
      console.log('ERROR:', err.message);
  });
}

0 个答案:

没有答案