Home > Mobile >  Why does my NodeJS Server make clients download the files?
Why does my NodeJS Server make clients download the files?

Time:09-30

I am using Express and NodeJS to create an API. But when I finished coding it, I opened the index, and instead of rendering the index file, it just made me download it. I could not find any errors causing this. Here is my code:

app.get("/", function(req,res){
  res.render("index", {name:auth.name})
}

The definition of app is express(), auth is SQLite DBWrapper

CodePudding user response:

There are either 3 scenarios:

  1. The file type is not recognizable (or the mime type) and so the server will think that the file is supposed to be downloaded (that is very unlikely because express is supposed to recognize .pug files)
  2. You did not app.use the pug parser
  3. If all above are incorrect, you either did not set the MIME type properly (maybe check your code twice).

If all of those are incorrect, maybe be more specific next time.

CodePudding user response:

The res.render() function is used to render a view and sends the rendered HTML string to the client. But for some reason, your code is downloading. Can you force the MIME Type to be text/html? Try this:

app.get("/", function (req, res) {
  res.contentType("text/html");
  res.setHeader("content-type", "text/html");
  res.render("index", { name: auth.name });
});
  • Related