📅  最后修改于: 2023-12-03 14:41:10.529000             🧑  作者: Mango
When sending data through a POST request, there are two common formats: application/x-www-form-urlencoded
and multipart/form-data
. In this article, we will focus on the former.
application/x-www-form-urlencoded
is a standard way of encoding data in an HTTP request payload. It is the default format used by most HTML forms, and is a simple way of sending key-value pairs to a server.
The payload format looks like this:
key1=value1&key2=value2&key3=value3
Each key-value pair is separated by an ampersand (&
), and the key and value are separated by an equal sign (=
).
To use fetch
with application/x-www-form-urlencoded
data, you need to construct the request payload in the correct format. You can do this manually, but there are also libraries available that can help.
Here is an example of how to use fetch
with application/x-www-form-urlencoded
data:
const formData = new URLSearchParams();
formData.append('username', 'john');
formData.append('password', 'secret');
formData.append('rememberMe', 'true');
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData.toString()
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we are sending a POST request to /api/login
with three key-value pairs: username
, password
, and rememberMe
. We first construct the payload using URLSearchParams
, and then call the toString()
method to convert it into the correct format. We also set the Content-Type
header to application/x-www-form-urlencoded
to tell the server what format the data is in.
application/x-www-form-urlencoded
is a simple and widely supported format for sending data in an HTTP request payload. Using fetch
with this format is relatively straightforward, and can be done using URLSearchParams
or by constructing the payload manually.