← Back to all snippets
JAVASCRIPT

Sending Authenticated POST Requests with JSON Payload

Discover how to send a POST request to an API with JSON data, applying a Bearer token for authentication using the JavaScript fetch API and proper headers.

async function postData(url, data, token) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(data)
    });

    if (!response.ok) {
      const errorBody = await response.json();
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorBody.message || 'Unknown error'}`);
    }

    const responseData = await response.json();
    console.log('POST request successful:', responseData);
    return responseData;
  } catch (error) {
    console.error('Error sending POST request:', error);
    throw error;
  }
}

// Usage example:
// const myData = { name: 'New Item', value: 123 };
// const userToken = 'your_jwt_token_here';
// postData('https://api.example.com/items', myData, userToken)
//   .then(response => console.log('Item created:', response))
//   .catch(error => console.error('Failed to create item:', error));
How it works: This snippet outlines how to send a POST request, which is crucial for creating or updating resources on an API. It properly sets the `Content-Type` header to `application/json` and serializes the JavaScript object into a JSON string for the request body. Crucially, it demonstrates how to include an `Authorization` header with a Bearer token, a common method for authenticating API requests.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs