【问题标题】:How to send HTTP headers in ReactJS using fetch()如何使用 fetch() 在 ReactJS 中发送 HTTP 标头
【发布时间】:2018-10-09 20:42:37
【问题描述】:
const URL = "http://url.com";
fetch(URL).then(res => res.json()).then(json => {
    this.setState({ someData: json });
});

如何发送带有 HTTP 标头的 HTTP 请求?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

试试这个

fetch('your_url', { 
   method: 'get', 
   headers: new Headers({
     // Your header content
   })
 });

【讨论】:

  • 为什么在这里使用new Headers?为什么不直接使用headers: { ... }
  • 检查github.github.io/fetch/#Headers,该选项可以采用对象或标题。也许 fetch api 在内部将对象转换为标头。因此,我已经通过直接标头来获取选项。
  • @konekoya Array 或 Headers 对象都可以接受
【解决方案2】:

您可以将它们传递给fetch()

const API = 'foo';

fetch(API, { headers: {
  'user-agent': 'Mozilla/4.0 MDN Example',
  'content-type': 'application/json'
}}).then()

您可以阅读更多关于 here 的信息。

【讨论】:

    【解决方案3】:

    fetch() 方法中你应该做这样的事情

    fetch(url, {
        ...    
        headers: {
           'user-agent': 'Mozilla/4.0 MDN Example',
           'content-type': 'application/json'
        }
    

    更多详情,请查看Mozilla Developers documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 2018-01-17
      • 2020-09-25
      • 2016-04-19
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多