发布于 2026-01-06 0 阅读
0

NodeJS:如何使用 Express 创建一个简单的服务器

NodeJS:如何使用 Express 创建一个简单的服务器

引言

于是我们在机器上安装了NodeJS 。

我们还学习了如何使用Node的HTTP模块创建一个简单的服务器

我们也知道如何获取外部软件包

现在我们想学习如何使用express创建一个简单的服务器。

编写一个简单的脚本

  • 打开终端
  • index.js创建一个名为:的文件
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • 将以下 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}/`);
});
Enter fullscreen mode Exit fullscreen mode

注意:这个简单的服务器只有一个可用的路由(/)。如果您想了解更多关于路由的信息,请阅读路由文档


从终端运行它。

  • 运行它:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • 结果:
Server running at: http://localhost:8080/
Enter fullscreen mode Exit fullscreen mode

现在您可以点击链接访问您创建的服务器。


延伸阅读


问题

  • 你使用过KoaSailsexpress之类的库吗?为什么使用它们?
文章来源:https://dev.to/miku86/nodejs-how-to-create-a-simple-server-using-express-1n9d