POSTing x-www-form-urlencoded Request with Fetch
To submit form-encoded parameters to a server using Fetch, you can utilize the following steps:
Define the request parameters:
const params = { 'userName': '[email protected]', 'password': 'Password!', 'grant_type': 'password' };
Set the request headers and method:
var obj = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, };
Encode the parameters using the URLSearchParams interface:
const encodedParams = new URLSearchParams(); params.forEach((value, key) => encodedParams.append(key, value));
Specify the body of the request:
obj.body = encodedParams.toString();
Finally, make the request:
fetch('https://example.com/login', obj) .then(function(res) { // Do stuff with result });
This process effectively encodes and includes the form-encoded parameters in the POST request, ensuring their submission to the server in a format compatible with your API.
The above is the detailed content of How to Submit x-www-form-urlencoded POST Requests with Fetch?. For more information, please follow other related articles on the PHP Chinese website!