简体   繁体   中英

Express Server returns Cannot Get when trying to access index.html

I referred to the previously asked question on this but couldnt resolve it. I have Express server installed and trying to run Index.html file through it. But I am getting 'Cannot GET /' as the response.

Here is the server.js through which I calling the index.html

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

app.get('index.html', function (req, res) {

  app.use("/", express.static(__dirname));
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

Thanks in advance!!

When you access a directory on your hosted site, say the root directory of localhost on port 8080, using http://localhost:8080/ for URL, the browser does not send a request for 'index.html` to the server and just uses whatever the server sends back.

It's the express static middleware which in response to a browser request with no filename will check if the folder exists and (by default) return any index.html contained in the folder. So your line of code for routing, app.get('index.html') never executes, and the browser gives you the error message.

Here's a mini static express server if you want to try it.

var express = require('express');
var app = express();
app.use(express.static('../public')); // path to your public directory

var server = app.listen(8080, function () {
   var host = server.address().address;
   var port = server.address().port;
   console.log('Example app listening at http://%s:%s', host, port);
 });

If you want a simple static, folder-as-server kind of thing, you can do it without express way like "/public":

var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");

var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);

I put this in the file express.js , so that is in the same folder than index.html (even associated .js with node.exe). This way the folder is the root of the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM