【问题标题】:Using FormData() inside fetch api is not working在 fetch api 中使用 FormData() 不起作用
【发布时间】:2020-10-20 00:30:47
【问题描述】:

我读了一遍,但找不到答案。

当我使用 FormData() 时,它返回状态 404 错误请求。

但是,如果我像 const requestBody(下面的示例)一样传递数据(硬编码),它会完美运行。

这是我的代码:

    var formData = new FormData();
    formData.append("nickname", "johxns");
    formData.append("password", "john_password");
    formData.append("email", "john@server.com");

    // If I do it this way, and assign this to body inside fetch, it works perfectly
    // const requestBody = '{"nickname": "johxns","password":"john_password","email":"john@server.com"}';

    fetch("http://localhost:5000/create_user", {
        // if instead of formData, I assign requestBody to body, it works!
        body: formData,
        headers: {
            "Content-Type": "application/json"
        },
        method: "POST"
    }).then(function(response) {
        return response.text();
    }).then(function(data){
        console.log('data', data);
    }).catch(function(err){
        console.err(err);
    });

我已经尝试过使用 URLSearchParams,但仍然无法使用。

谢谢。

【问题讨论】:

  • 你试过将formData转成json吗?
  • 好吧,如果它以一种方式而不是另一种方式工作,我会坚持这种工作方式......有什么问题?

标签: javascript fetch form-data


【解决方案1】:

如果您不发送 json,则不应将 Content-Type 标头设置为 application/json。根据this 的回答,你不需要设置Content-Type 标头。

正文数据类型必须匹配“Content-Type”标头

Using Fetch

【讨论】:

    【解决方案2】:

    如果您将Content-Type 设置为application/json,您应该发送 json 数据;如果使用 FormData API,您应该不设置任何 Content-Type,因为 fetch 函数能够确定正确的 Content-Type

    更多信息请参见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-15
      • 2021-08-05
      • 2018-02-16
      • 2012-03-23
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多