I'm really new to node/express and I'm trying to understand how sending static files work. I managed to serve my index file, but I cannot serve other files as response of a GET request.
app.use(express.static(path.join(__dirname, '/client/build')))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '.', 'client/build/', 'index.html'))
res.end()
})
app.get('/portfolio', (req, res) => {
const person = req.query.name
var filePath = __dirname + '/client/build/' + person + '/' + 'index.html'
res.sendFile(filePath)
res.end()
})
I found similar questions but nothing seems to work.
The request I send is:
fetch(`portfolio?name=${who}`)
There's a few problems with your code. One of them is that you end the request before the file is even done sending and another problem is that you're not using the res.sendFile
method properly.
try something like this:
app.get('/', (req, res) => {
const fileDirectory = path.resolve(__dirname, '.', 'client/build/');
res.sendFile('index.html', {root: fileDirectory}, (err) => {
res.end();
if (err) throw(err);
});
})
app.get('/portfolio', (req, res) => {
const person = req.query.name
const fileDirectory = __dirname + '/client/build/' + person + '/';
res.sendFile('index.html', {root: fileDirectory}, (err) => {
res.end();
if (err) throw(err);
});
})
I don't recommend throwing an error whenever you get one but it should at least give you an idea how you can get this to work.
I finally solved it by using this on the server:
app.use( express.static(path.join(__dirname, 'client/build/person1')))
app.use( express.static(path.join(__dirname, 'client/build/person2')))
and calling it in the view like this:
<a href='/person1'></a>
<a href='/person2'></a>
As it seems, express.static resolves the paths on its own, so you don't need to handle the request yourself to serve the static files.
If this is not a good solution please coment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With