[英]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.
我已经安装了Express服务器,并试图通过它运行Index.html文件。 But I am getting 'Cannot GET /' as the response.
但我得到“无法获取/”作为响应。
Here is the server.js through which I calling the index.html 这是server.js,通过它我称为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. 当访问托管站点上的目录时,例如使用端口
http://localhost:8080/
表示端口8080上localhost的根目录,浏览器不会向服务器发送“ index.html”请求,使用服务器发回的任何内容。
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. 这是快速静态静态中间件,它会响应没有文件名的浏览器请求,将检查该文件夹是否存在,并(默认情况下)返回该文件夹中包含的任何index.html。 So your line of code for routing,
app.get('index.html')
never executes, and the browser gives you the error message. 因此,用于路由的代码行
app.get('index.html')
永远不会执行,浏览器会向您显示错误消息。
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": 如果您想要一种简单的静态的,服务器文件夹式的东西,则可以不用“ / 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). 我把它放在文件
express.js
,所以它和index.html
在同一文件夹中(甚至与node.exe相关联的.js
)。 This way the folder is the root of the server. 这样,文件夹是服务器的根目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.