Created
March 6, 2023 16:10
-
-
Save chrispage1/6b642fab836c0bfc4867bac97f92336f to your computer and use it in GitHub Desktop.
Simple Express File Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bearerToken = 'secretTokenGoesHere'; | |
const httpPort = 80; | |
// load in express & express fileUpload | |
const express = require('express'), | |
fileUpload = require('express-fileupload'), | |
app = express(); | |
// initialise fileUpload plugin | |
app.use(fileUpload()); | |
// when a post request comes into store, lets handle the file | |
app.post('/store', (req, res) => { | |
// verify the bearer token | |
const authToken = req.header('Authorization'); | |
if (authToken?.split(' ')[1] !== bearerToken) { | |
return res.status(403).json({ | |
success: false, | |
message: 'Unauthorized' | |
}); | |
} | |
// check we have some files | |
if (req.files?.file) { | |
// move the file into our files directory | |
const file = req.files.file; | |
file.mv(__dirname + '/files/' + file.name); | |
// send a success message back | |
return res.send({ | |
success: true, | |
message: 'File has been received', | |
}) | |
} | |
// output an error message | |
return res.status(422).json({ | |
success: false, | |
message: 'No file payload received' | |
}); | |
}); | |
// start listening | |
app.listen(httpPort, () => { | |
console.log('App is listening in port ' + httpPort); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment