Home >Web Front-end >JS Tutorial >How do you send form-encoded data with Fetch API?
When making POST requests, you might need to include form-encoded data in your payload. Here's how to handle this using the Fetch API:
You can easily include form-encoded parameters in your request using the URLSearchParams object. Here's an example:
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' }) });
This will encode your parameters as 'userName=[email protected]', 'password=Password!', and 'grant_type=password', and append them to the request body.
For more information on the WindowOrWorkerGlobalScope.fetch method, refer to the Mozilla Developer Network documentation: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
The above is the detailed content of How do you send form-encoded data with Fetch API?. For more information, please follow other related articles on the PHP Chinese website!