How to display style and run javascript along with html on Node Js?

Asked

Viewed 596 times

2

I started to learn Ode js, but I face a problem when rendering a project composed of: Html, css and javascript. HTML is uploaded and opens, but css doesn’t work like javascript does.

codigo Node:

var express = require("express");
app = express();

app.get("/", function(req,res){
res.sendFile(__dirname + "/html/index.html")
res.sendFile(__dirname + "/html/estilo.css")
res.sendFile(__dirname + "/html/script.js")
})


app.listen(3000);
  • express only sends one file. You can use src and the link to the.css style and the.js script in index.html

  • In case I have to put css and js inline? But there is no way to use css externally? It can be by other methods outside the express

  • You have to put it in index.html. There is no other way in express.

1 answer

1


The server serves one file per request. It can serve more than one at a time, but it will be with parallel requests where only one file is sent per request.

In practice this means that you should load the html file which in turn asks the server for the other files... something like this:

var express = require("express");
app = express();

app.get("/", function(req,res){
    res.sendFile(__dirname + "/html/index.html")
})
app.get("/estilo.css", function(req,res){
    res.sendFile(__dirname + "/html/estilo.css")
})
app.get("/script.js", function(req,res){
    res.sendFile(__dirname + "/html/script.js")
})

app.listen(3000);

express has a tool for these static files, you pass the directory, in your case html and it’s done:

var express = require("express");
app.use(express.static('html'))
app = express();

app.get("/", function(req,res){
    res.sendFile(__dirname + "/html/index.html")
})

app.listen(3000);

And if the requested route is directly /index.html he doesn’t even run that app.get("/",.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.