如何使用 Node/Express 为我的 Web 应用程序提供服务
How can I serve my web app with Node/Express?
我可能会问一个巨大的菜鸟问题,这是我在这里问过的最糟糕的问题之一,但我迷失了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。我建议您查看其中之一,这对构建应用程序网页有很大帮助。
- 在Web应用程序中使用Highcharts javascript
- 将下载链接从web浏览器传递给第三方应用程序
- 在web应用程序中的新搜索中重新加载搜索结果(不带jQuery)
- Web应用程序,将成员状态更新为其他成员
- 同一文本框中的验证程序CPF e CNPJ(ASP.NET web应用程序)
- web浏览器中的离线应用程序存储数据并在之后上传
- 使用Ember的Web应用程序架构.动画逻辑应该放在哪里
- 如何使用默认的网络摄像头拍摄照片并将其保存在我的c#.net web应用程序中
- c#web应用程序中的条形码打印
- 使用javascript为web应用程序自定义键盘快捷键
- 使用angularjs和node.js时的Web应用程序文件夹结构
- PhpWindows 8.1版本上的Javascript web应用程序
- 是否有任何开源web应用程序具有良好的QUnit(或JSUnit)测试用例
- Project和作为web应用程序发布的多个doGet()脚本文件——需要澄清
- 无法在Windows 10 Cordova应用程序中从Web视图进行ajax调用
- 如何获取使用我们的脚本或web应用程序的网站名称
- 没有框架/DLL的VS Web应用程序项目
- 正确传输和保护用户'web应用程序的密码
- 检查Progressive web应用程序中的网络更改
- 如何在应用程序>Web浏览器控件中使用Google Maps API v3 ClientID