Cannot GET /index.html Node JS error

Asked

Viewed 4,910 times

0

Estrutura da aplicação

Codigo do servidor

Servidor a correr

Quando tento aceder a página index.html

I think the problem is the assignment of routes, something I’ve been trying to do but without success.

  • 1

    There is no route rendering this page. There is no route for this index.html. For example app.get('/index', function(req, res) {
 res.sendfile('public/index.html')
}).

  • I made this route app.get('/', Function(req, res) { res.sendfile('./index.html') }) and when I try to access localhost:3000/index.html keeps giving the same error

  • From a searched how it loads pure html file, I make use of view engine, so it’s not the same thing to render html. You have to load the public folder into the express to load what’s inside it as well.

  • 1

    Following the friend’s comment above, you should access "http://localhost:3000/index" and not "http://localhost:3000/index.html". The route that was created is "/index" and not "/index.html".

2 answers

1

Put this piece of code:

const express = require("express");

const app = express();

app.use(express.static(__dirname));

But I strongly recommend serving static files inside a folder, for more code organization:

const express = require("express");
const path = require("path");

const app = express();

app.use(express.static(path.join(__dirname, "public")));

app.listen(3000);

The . html files will be inside the folder /public. In the two examples, you will access http://localhost:3000

But, if you want to access, for example: http://localhost:3000/site, you will use app.use("/site", express.static(path.join(__dirname, "public")));, thus:

const express = require("express");
const path = require("path");

const app = express();

app.use("/site", express.static(path.join(__dirname, "public")));

app.listen(3000);

Access http://localhost:3000/site

In the first argument of the function use, is the endpoint address that will be accessed by the user, and in the second argument is the location of the static files that will be served to the client.

To better understand, if you put "/site/api/v2" instead of "/site", you will access the following URL: http://localhost:3000/site/api/v2 and if you put path.join(__dirname, "public", "static"), in your project you will put the static files in /public/static (files .html, .css, .js, among others)

That’s it. :)

1

Boas Alexandre,

i think the problem is that the file "index.html" is not being sent to when the GET request.

var path = require('path');

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

I hope I’ve helped :)

Browser other questions tagged

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