首页 > 解决方案 > fetchAPI 的 Headers 对象始终为空

问题描述

我有这个请求函数,它是 fetch API 的包装器,用于向我的 API 发出请求。但是当我的前端应用程序发出请求时,标头对象始终为空。我究竟做错了什么 ?

export function request(method, url, payload) {
  const body = JSON.stringify(payload);
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  const parameters = {
    headers: headers,
    method: method,
    body: body,
    cache: "default"
  };
  return Observable.create(observer => {
    fetch(url, parameters)
      .then(response => {
        observer.next(response);
        observer.complete();
      })
      .catch(error => {
        observer.error(error);
      });
  });
}

标签: javascriptrestecmascript-6

解决方案


试着让它成为一个简单的对象:

const headers = {
    "Content-Type": "application/json"
};

推荐阅读