此 fetch API Javascript 代码中的 Content-type 标头应该是什么?

问题描述 投票:0回答:2
    fetch(url, {
      method: 'post',
      headers: {
        "Content-type":
      },
      body: 'bar= foo& lorem=ipsum'

    })

应该是吗?

A)

application/x-www-form-urlencoded; charset=UTF-8

B)

text/html; charset=utf-8

C)

application/json; charset=UTF-8

D)

Content-Type: multipart/form-data; boundry=something

我刚刚开始学习 JavaScript 和 API。在查看 MDN 文档时,我发现标头中有不同的选项。只是困惑该使用哪一个?

javascript api fetch-api asynchronous-javascript
2个回答
2
投票

key=value
分隔的
&
参数序列是参数的 URL 编码格式。所以A是正确答案。


0
投票

如果您发送 url 编码数据(ex:

key=value& key=value
),则
Content-Type
将是:

  • A) application/x-www-form-urlencoded;字符集=UTF-8

如果您发送 html 数据(ex:

<h1>hello</h1>
),则
Content-Type
将是:

  • B)文本/html;字符集=utf-8

如果您发送 json 数据(ex:

{"name" : "anyName"}
),则
Content-Type
将是:

  • C) application/json;字符集=UTF-8

如果您发送表单数据+文件(例如:

new FormData(document.getElementById('form1'))
)那么您不需要手动设置
Content-Type
,即:

  • D)多部分/表单数据;边界=某物
© www.soinside.com 2019 - 2024. All rights reserved.