In API-based applications, sending a token in the HTTP header is standard procedure for authorization and authentication. Here are examples using different methods to include this token in requests for API-based applications.
1. JavaScript Fetch API
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2. Axios
import axios from 'axios';
axios.get('https://api.example.com/data', {
headers: {
'Authorization': `Bearer your_token_here`
}
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
3. cURL
curl -H "Authorization: Bearer your_token_here" -H "Content-Type: application/json" https://api.example.com/data
4. Node.js
To verify tokens on the server side in an Express app:
app.get('/data', (req, res) => {
const token = req.headers['authorization']?.split(' ')[1];
if (token) {
// Verify the token here
res.send('Token received and verified.');
} else {
res.status(403).send('No token provided.');
}
});