POSTing x-www-form-urlencoded Data with Fetch
In the realm of web development, HTTP requests often carry form-encoded data to servers. To achieve this using the Fetch API, let's explore how to construct such a request.
Consider the scenario where you have parameters like user name, password, and grant type that need to be sent as form-encoded data to a server. You've set up the request with the appropriate headers, but how can you incorporate the parameters?
To do so, you can harness the power of URLSearchParams. Here's how:
fetch('https://example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ 'userName': '[email protected]', 'password': 'Password!', 'grant_type': 'password' }) });
The URLSearchParams object serves as a container for your parameters. It automatically URL-encodes the values, making them ready for transmission. By setting the Content-Type header appropriately, your request now carries the encoded data to the server.
The above is the detailed content of How to POST x-www-form-urlencoded Data with Fetch?. For more information, please follow other related articles on the PHP Chinese website!