Node.js Hello World with Express
示例
下面的示例使用Express创建一个侦听端口3000的HTTP服务器,该服务器响应“Hello,World!”。Express是常用的Web框架,可用于创建HTTPAPI。
首先,创建一个新文件夹,例如myApp。进入myApp并制作一个包含以下代码的新JavaScript文件(hello.js例如,以其命名)。然后npminstall--saveexpress从命令行使用Express模块安装。有关如何安装软件包的更多信息,请参考此文档。
//导入快递的顶级功能
const express = require('express');
//使用顶层功能创建Express应用程序
const app = express();
//将端口号定义为3000
const port = 3000;
// Routes HTTP GET requests to the specified path "/" with the specified callback function
app.get('/', function(request, response) {
response.send('Hello, World!');
});
//使应用程序在端口3000上监听
app.listen(port, function() {
console.log('Server listening on http://localhost:' + port);
});在命令行中,运行以下命令:
node hello.js
打开浏览器,浏览至http://localhost:3000或http://127.0.0.1:3000查看响应。
有关Express框架的更多信息,可以检查带有Express的Web应用程序部分