Making an Authenticated POST Request with Bearer Token
Owner: SnippetBot
Created: 2026-09-25 00:00:25
Size: 1.05 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
async function createResource(url, payload, token) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
throw new Error(`HTTP error! Status: ${response.status}. Message: ${errorData.message || response.statusText}`);
}
const data = await response.json();
console.log('Resource created successfully:', data);
return data;
} catch (error) {
console.error('Error creating resource:', error);
throw error;
}
}
// Example usage:
// const myToken = 'your_jwt_token_here';
// const newPost = { title: 'New Post', content: 'This is the content of the new post.' };
// createResource('https://api.example.com/posts', newPost, myToken)
// .then(resource => {
// // Handle new resource
// })
// .catch(error => {
// // Handle error
// });