Here is my backend code. It has 2 protected routes. Authorization Header is needed (Bearer token).
- These routes allows you to download your photo and your cv.
I have no issue with my backend. It is working with postman and mobile applications. I think there is a limitation for frontend.
I do NOT want
- I don't want to use fetch to download these files as blob. Because it doesn't allow to browser to show its progress bar.
- I don't want to change my authentication method from Bearer token to cookie. I can already do this with cookie.
I wonder why Bearer token is more popular than cookie If I have to use cookie to make this happen.
Backend
// other imports .....
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
app.use((req, res, next) => {
try {
const token = req.get('Authorization');
if(!token) {
throw new Error('401');
}
const userId = getIdFromToken(token);
if(!userId) {
throw new Error('401');
}
res.locals.userId = userId;
next();
} catch (error) {
next(error);
}
})
app.get('/api/me/photo', (req, res) => {
const userId = res.locals.userId;
const imagePath = path.resolve(process.env.DISC_PATH, 'images', `${userId}.png`);
res.attachment('me.png');
res.set('Content-Type', 'image/png');
const stream = fs.createReadStream(imagePath);
res.pipe(stream);
})
app.get('/api/me/cv', (req, res) => {
const userId = res.locals.userId;
const pdfPath = path.resolve(process.env.DISC_PATH, 'cv', `${userId}.png`);
res.attachment('my-cv.pdf');
res.set('Content-Type', 'application/pdf');
const stream = fs.createReadStream(pdfPath);
res.pipe(stream);
})
...
// error handling, etc...
Frontend
<html>
<body>
<!-- How can I send the Authorization header here -->
<img src="/api/me/photo" />
<!-- How can I send the Authorization header here -->
<a href="/api/me/cv">Download My CV</a>
<!-- How can I send the Authorization header here -->
<button id="btn"> Download My CV (V2) </button>
<script>
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
// How can I send the Authorization header here
window.open('/api/me/cv');
});
</script>
</body>
</html>