如何使用 Node/Express 为我的 Web 应用程序提供服务

How can I serve my web app with Node/Express?

本文关键字:应用程序 Web 服务 我的 何使用 Node Express      更新时间:2023-09-26

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

我的文件夹树如下:

  • 万维网
    • 节点服务器.js
    • (更多内容)
    • Liteconomy(我的网络应用程序)
      • .js
      • .css
      • 插件
      • 模板
      • 索引.html
      • sublime_project

很典型吧?好吧,我一直在搜索如何通过简单的访问来提供此应用程序,例如localhost:8080/Liteconomy或 localhost:8080/Liteconomy.html。在那之后,我的角度路由将完成剩下的工作,但我就是无法提供应用程序。

我在节点服务器中写了这个.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"错误。

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

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

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

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

然后,如果您要访问您设置和移植的URL,您将能够访问。

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

希望对您有所帮助!

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

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

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

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

"__dirname"代表您的根目录路径,然后您只需输入文件路径即可。

希望有帮助!

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