如何使用Node / Express提供我的Web应用程序?

时间:2016-02-26 10:21:22

标签: javascript node.js express

我可能会问一个巨大的菜鸟问题,这是我曾经问过的最糟糕的问题之一,但是我和Node / Express一样迷失了。我只使用Apache服务器(典型的WAMP / XAMP用于测试目的),所以我完全不知道我必须做什么来提供我的网络应用程序。

我的文件夹树如下:

  • WWW
    • nodeserver.js
    • (更多内容)
    • Liteconomy(我的网络应用)
      • JS​​
      • CSS
      • 插件
      • 模板
      • 的index.html
      • sublime_project

非常典型,是吧?好吧,我一直在寻找如何通过像localhost:8080 / Liteconomy或localhost:8080 / Liteconomy.html这样的简单访问来提供这个应用程序。在那之后,我的角度路由将完成其余的工作,但我无法为该应用程序提供服务。

我用nodeserver.js编写了这个:

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

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(8080, function () {
  console.log('Example app listening on port 8080!');
});

app.get('/Liteconomy', function (req, res) {
  res.send('Liteconomy/index.html');
});

当我执行它并访问localhost:8080时,我得到了“Hello world”,但是当我转到localhost:8080 / Liteconomy时,我得到以下纯文本:“Liteconomy / index.html”。如果我尝试直接访问索引资源,我会收到“无法获取/Liteconomy/index.html”错误。

我也试过使用静态的东西,但也没用。

我在这里做错了什么?我想我只是缺少一些非常重要的东西。

2 个答案:

答案 0 :(得分:1)

执行以下操作,它将解决您的问题。

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();


 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(cookieParser());

// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));

//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));

// Rest of the stuff

然后,如果您要访问您设置和移植的网址,您就可以访问。

建议使用express.static来提供静态内容。

希望它有所帮助!

答案 1 :(得分:-1)

你得到一个纯文本答案,因为你实际上要求用:

来做
app.get('/Liteconomy', function (req, res) {
   res.send('Liteconomy/index.html');
});

如果你想发送一个像index.html文件这样的简单html文件,你应该使用" sendfile"功能:

app.get('/Liteconomy', function (req, res) {
   res.sendfile(__dirname + '/Liteconomy/index.html');
});

" __目录名称"表示您的根目录路径,然后您只需放置文件路径。

希望有所帮助!

PS:默认快递带有jade和ejs模板支持,而不仅仅是使用html。我建议你看看其中一个,这对构建你的应用程序网页有很大的帮助。

相关问题