Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node/Express send static file on request

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}`)
like image 819
Braian Avatar asked Sep 16 '17 19:09

Braian


2 Answers

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.

like image 93
user3254198 Avatar answered Sep 23 '22 21:09

user3254198


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

like image 23
Braian Avatar answered Sep 25 '22 21:09

Braian