10

I'm trying to run my first express app, but can't seem to get my webpage to show. I have the following code:

var fs = require("fs");
var config = JSON.parse(fs.readFileSync("files/config.json"));  
var host = config.host;
var port = config.port;
var express = require("express");

var app = express();

app.use(app.router);
app.use(express.static(__dirname + "/public"));

app.get("/", function(request, response){
    response.send("hello!");
});

app.listen(port, host);
console.log("Listening on port" + port);

Here is my directory tree

nodejs/
    js/
        javascript.js
    public/
        index.html

I know the server is running because I get my "Hello!" response in the browser when I run 127.0.0.01:1337

But when I try and type the webpage 1227.0.0.1:1337/index.html, I get Cannot GET /index.html displayed in the browser

So I'm guessing it's something wrong with the name value in my get method, but can't figure out what it is and how to fix it.

4

2 回答 2

17

您的应用只会路由在您app.use(app.router)通话时设置的页面请求。因此,将您的app.use呼叫重新排序为以下之一:

快递 3

app.use(express.static(__dirname + "/public"));
app.use(app.router);

__dirname是执行脚本所在的目录,因此因为它位于js与您的代码对等的目录中,所以public需要:

app.use(express.static(__dirname + "/../public"));
app.use(app.router);

快递4

Express 4无需手动执行app.use(app.router). 使用 Express 4,您只需要:

app.use(express.static(__dirname + "/../public"));

于 2013-10-27T16:34:18.680 回答
0

我遇到了这个问题....经过很多麻烦后,我发现如果您在 t 时间运行两个工作区或项目,那么它将创建这种情况。所以你可能一次只打开一个工作区而不仅仅是文件...打开洞文件夹然后运行特定的文件。在你的 VS 代码设置中进行以下更改。

设置设置

对于 64 位系统。

{
    "liveServer.settings.AdvanceCustomBrowserCmdLine: ": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
    "liveServer.settings.NoBrowser": false
}

对于 32 位系统。

{
    "liveServer.settings.AdvanceCustomBrowserCmdLine: ": "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    "liveServer.settings.NoBrowser": false
}
于 2018-05-03T18:10:25.767 回答