在Nodejs中无法使用Express显示index.html [英] Can't get index.html to show with Express in Nodejs

查看:490
本文介绍了在Nodejs中无法使用Express显示index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行我的第一个快速应用程序,但似乎无法让我的网页显示。我有以下代码:

  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);

这是我的目录树

  nodejs / 
js /
javascript.js
public /
index.html
code> 127.0.0.01:1337



但是当我尝试并键入网页 1227.0.0.1: 1337 / index.html ,我得到无法在浏览器中显示GET /index.html



所以我猜想我的 get 方法中的名称的值是错误的,但是不能弄清楚它是什么,以及如何解决它。

解决方案

您的应用程序只会路由当时设置的页面请求的 app.use(app.router)调用。所以重新排序你的 app.use 调用是以下之一:



Express 3



  app.use(express.static(__ dirname +/ public)); 
app.use(app.router);

__ dirname 是执行脚本所在的目录,因为它存在于您的代码将需要:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ p> app.use(express.static(__ dirname +/../public));
app.use(app.router);



Express 4



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



app.use(express_static(__ dirname +/../public\"));


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.

解决方案

Your app will only route page requests that are set up at the time of your app.use(app.router) call. So reorder your app.use calls to be one of the following:

Express 3

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

__dirname is the directory that the executing script resides in, so because that lives in the js directory that's a peer to public your code would need to be:

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

Express 4

Express 4 removes the need to manually do app.use(app.router). With Express 4 you just need:

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

这篇关于在Nodejs中无法使用Express显示index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆