javascript - 使用 express.js 和 node.js 运行我的示例应用程序

标签 javascript node.js

var sys = require("sys"),  
my_http = require("http");  
my_http.createServer(function(request,response){  
    sys.puts("I got kicked");  
    response.writeHeader(200, {"Content-Type": "text/plain"});  
    response.write("Hello World");  
    response.end();  
}).listen(8080);  
sys.puts("Server Running on 8080");

以上是我的基本网络服务器,现在我想运行我的应用程序,其中包含一个 HTML 和一个 JS 文件。我应该把这些文件放在哪里,以便我可以通过我的端口访问它。

我使用 Apache and Xampp ,所以我将文件放在 htdocs 中目录并通过我的浏览器访问它,但在 node.js 方面我完全糊涂了?

最佳答案

让我们一步一步来。

确定您的应用程序的位置。

首先确定您的应用程序所在的位置。我们将其作为 C:\your_app。路径并不重要,因此请随意将目录定位到最适合您的位置。

安装 Node.js

我们将在此处设置 Node.js 和 Express。 Node.js 是一个框架,Express 提供了一个 Web 服务器。我们需要的 Web 服务器不需要做任何花哨的事情。 Web 服务器需要的唯一功能是提供静态文件的能力。

要开始下载并安装 Node.JS:http://nodejs.org/

安装 Express

Express 是一个在 Node.js 中执行的包。要安装 express,请在命令提示符中导航到应用程序的目录 c:\your_app。

现在让将Express 安装为Node.js 的一个包。 在命令提示符下键入“npm install express”。安装了 Express 并且应该创建了一个名为 “node_modules” 的目录。

server.js

现在 Express 已安装,我们需要将其配置为作为网络服务器执行。在 c:\your_app 目录中创建另一个名为“server.js”的文件。

var express = require('express');
var app = express();
port = process.argv[2] || 8000;

app.configure(function () {
    app.use(
        "/", //the URL throught which you want to access to you static content
        express.static(__dirname) //where your static content is located in your filesystem
    );
});
app.listen(port); //the port you want to use
console.log("Express server running");

在 Node.js 中启动 Express Web 服务器

在命令提示符中确认您位于 c:\your_app 目录并执行以下命令。

node server.js 8000

现在 Web 服务器应该在端口 8000 上运行,您的 index.html 页面应该显示在浏览器中

关于javascript - 使用 express.js 和 node.js 运行我的示例应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18784873/

相关文章:

javascript - 如何制作按钮的 "pushed"效果?

node.js - 如何检查电子邮件是否存在,如果存在则抛出错误,如果与 Sequelize 和 Express 不匹配则创建用户?

javascript - webpack 动态模块加载器通过 require

javascript - Passport Strategy中的 "done"回调函数是什么配置 "use"函数

javascript - 使用 IDE (Node) 读取本地存储的 JSON 文件

javascript - 识别项目中未使用的 JS 脚本文件

javascript - 将函数绑定(bind)到 jPlayer 的 "next"控件

javascript - 查询 : Get div defined in same table row

javascript - 使用 html-pdf 后 Sails EJS-view 不渲染图像

javascript - 刷新页面显示找不到文件错误如何使用 [angular js + NodeJS/ExpressJS] 解决