我的代码:

fetch("api/xxx", {
    body: new FormData(document.getElementById("form")),
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        // "Content-Type": "multipart/form-data",
    },
    method: "post",
}

我尝试使用fetch api发布我的表单,它发送的正文是这样的:

-----------------------------114782935826962
Content-Disposition: form-data; name="email"

test@example.com
-----------------------------114782935826962
Content-Disposition: form-data; name="password"

pw
-----------------------------114782935826962--

(我不知道为什么每次发送的时候boundary里的数字都会变…)

我想用“Content-Type”:“application/x-www-form-urlencoded”发送数据,我该怎么做?或者如果我必须处理它,我如何解码控制器中的数据?


请回答我的问题,我知道我能做到:

fetch("api/xxx", {
    body: "email=test@example.com&password=pw",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    method: "post",
}

我想要的是像$(“#form”).serialize()在jQuery (w/o使用jQuery)或解码控制器中的多部分/表单数据的方法。谢谢你的回答。


当前回答

MDN上有一些说明,浏览器将自动处理Content-Type:

如果字典中没有设置内容类型头,请求也会自动设置一个内容类型头。

所以当我们发送一个取回请求时,我们不需要指定'content-type'。

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('Success:', result);
})
.catch(error => {
  console.error('Error:', error);
});

如果在头文件中设置content-type。浏览器将不会尝试分割请求有效负载中的表单数据。

我使用fathcer来处理FormData,与XHR的行为相同。

import { formData } from '@fatcherjs/middleware-form-data';
import { json } from '@fatcherjs/middleware-json';
import { fatcher } from 'fatcher';

fatcher({
    url: '/bar/foo',
    middlewares: [json(), formData()],
    method: 'PUT',
    payload: {
        bar: 'foo',
        file: new File()
    },
    headers: {
        'Content-Type': 'multipart/form-data',
    },
})
    .then(res => {
        console.log(res);
    })
    .catch(err => {
        console.error(error);
    });

其他回答

使用FormData和fetch来抓取和发送数据

fetch(form.action, {method:'post', body: new FormData(form)});

函数send(e,form) { fetch(形式。action,{方法:'post', body: new FormData(form)}); console.log('我们异步发送帖子(AJAX)'); e.preventDefault (); } <form method="POST" action="myapi/send" onsubmit="send(event,this) "" > <input hidden name="csrfToken" value="a1e24s1"> <input name="email" value="a@b.com"> <input name="phone" value="123-456-789"> < input type = " submit " > > < /形式 在chrome控制台>网络之前/之后“提交”

使用fetch api,你不需要包含“Content-type”:“multipart/form-data”的头文件。

所以下面的工作:

let formData = new FormData()
formData.append("nameField", fileToSend)

fetch(yourUrlToPost, {
   method: "POST",
   body: formData
})

注意,对于axios,我必须使用content-type。

为了补充上述好的答案,你也可以避免在HTML中显式设置动作,并使用javascript中的事件处理程序,使用"this"作为表单来创建"FormData"对象

Html表格:

<form id="mainForm" class="" novalidate>
<!--Whatever here...-->
</form>

在JS中:

$("#mainForm").submit(function( event ) {
  event.preventDefault();
  const formData = new URLSearchParams(new FormData(this));
  fetch("http://localhost:8080/your/server",
    {   method: 'POST',
        mode : 'same-origin',
        credentials: 'same-origin' ,
        body : formData
    })
    .then(function(response) {
      return response.text()
    }).then(function(text) {
        //text is the server's response
    });
});

@ kamilkieczzewski回答是伟大的,如果你是表单数据格式是在表单多部分风格,但如果你需要提交的表单查询参数风格:

如果您希望以使用简单GET提交的方式生成查询参数,也可以将FormData直接传递给URLSearchParams构造函数。

        form = document.querySelector('form')
        const formData = new FormData(form);
        formData["foo"] = "bar";
        const payload = new URLSearchParams(formData)
        fetch(form.action, payload)

客户端

不要设置内容类型标头。

// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');

fetch("api/SampleData",
    {
        body: formData,
        method: "post"
    });

服务器

使用FromForm属性指定绑定源为表单数据。

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpPost]
    public IActionResult Create([FromForm]UserDto dto)
    {
        return Ok();
    }
}

public class UserDto
{
    public string Name { get; set; }
    public string Password { get; set; }
}