用Node快速写API

本文最后更新于:几秒前

快速写API

以 Express 框架为例

首先,确保已经安装了 Node.js,然后新建一个文件夹,在命令行中进入该文件夹后执行npm init -y初始化项目,接着安装 Express:npm install express

创建一个名为app.js的文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const express = require('express');
const app = express();
const port = 8081;
const multer = require('multer');
const fs = require('fs');
const path = require('path');

// 假设你的HTML文件在项目目录下的public文件夹中的index.html
app.get('/index', (req, res) => {
const htmlPath = path.join(__dirname, 'public', 'index.html');
res.sendFile(htmlPath);
});

// 创建一个简单的GET请求API
app.get('/api/greet', (req, res) => {
res.send('Hello, huangjinyan!');
});

// 创建一个返回JSON数据的API
app.get('/api/user', (req, res) => {
const user = {
name: "李明~",
age: 30
};
res.json(user);
});

// 下载文件
app.get('/api/download', (req, res) => {
const filePath = path.join(__dirname, 'files', 'example.txt');
const fileName = 'example.txt';
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.setHeader('Content-Type', 'application/octet-stream');
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.status(404).send('File not found');
return;
}
const fileStream = fs.createReadStream(filePath);
fileStream.pipe(res);
});
});



// 启动服务器并监听端口
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

在上述代码中:

  1. 引入express模块并创建一个app实例。
  2. 定义了一个端口号3000
  3. 通过app.get方法创建了一个GET请求类型的 API。当访问/api/greet路径时,服务器会返回Hello, World!的响应。
  4. 当访问/api/user路径时,服务器会返回一个包含用户信息的 JSON 对象。
  5. 亦可打开指定网页
  6. 下载文件
  7. 最后,使用app.listen启动服务器并监听指定端口,在控制台打印服务器运行的地址。

image-20241107132444122


用Node快速写API
https://yan-sheng-li.github.io/blog/posts/52388.html
作者
李延胜
发布于
2024年11月8日
许可协议