const apiUrl = 'https://api.example.com/data';
const requestData = {
name: 'John Doe',
age: 30,
};
// Send a POST request using fetch
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Specify JSON content type
},
body: JSON.stringify(requestData), // Convert data to JSON string
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Success:', data); // Handle successful response
})
.catch(error => {
console.error('Error:', error); // Handle errors
});
POST Request with Fetch API and JSON Data
Related Posts
More content you might like
Tutorial
javascript
JavaScript in Modern Web Development
JavaScript isn't limited to the browser anymore. It's being used in diverse domains:
- Tools like React Native enable building native apps using JavaScript.
- Example: Facebook's mobile app.
Dec 10, 2024
Read More Code
javascript
Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling
responsive: truemakes the table adapt to different screen sizes.
serverSide: trueenables server-side pagination, sorting, and filtering.processing: truedisplays a processing indicator while fetching data.
Oct 24, 2024
Read More Tutorial
php
Handling HTTP Requests and Raw Responses in Laravel
When working with OAuth or JWT-based APIs, you may need to pass a Bearer Token for authentication.
use Illuminate\Support\Facades\Http;
$response = Http::withToken('your-bearer-token')->post('https://api.example.com/endpoint', [
'key1' => 'value1',
'key2' => 'value2',
]);
dd($response->body());Oct 24, 2024
Read More Article
javascript
20 Useful Node.js tips to improve your Node.js development skills:
No preview available for this content.
Oct 24, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!