NodeJS:如何使用 Express 创建一个简单的服务器
引言
于是我们在机器上安装了NodeJS 。
我们还学习了如何使用Node的HTTP模块创建一个简单的服务器。
我们也知道如何获取外部软件包。
现在我们想学习如何使用express创建一个简单的服务器。
编写一个简单的脚本
- 打开终端
index.js创建一个名为:的文件
touch index.js
- 将以下 JavaScript 代码添加到其中:
// import express (after npm install express)
const express = require('express');
// create new express app and save it as "app"
const app = express();
// server configuration
const PORT = 8080;
// create a route for the app
app.get('/', (req, res) => {
res.send('Hello World');
});
// make the server listen to requests
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
注意:这个简单的服务器只有一个可用的路由(/)。如果您想了解更多关于路由的信息,请阅读路由文档。
从终端运行它。
- 运行它:
node index.js
- 结果:
Server running at: http://localhost:8080/
现在您可以点击链接访问您创建的服务器。