
免费API拦截工具入门指南:初学者必备教程与实用技巧
AWS Lambda 是 Amazon Web Services (AWS) 提供的一项无服务器计算服务,允许在无需预置或管理服务器的情况下运行代码。Node.js 是基于 Chrome V8 JavaScript 引擎构建的 JavaScript 运行时。结合使用 AWS Lambda 和 Node.js 可以创建由 HTTP 请求等事件触发的 RESTful API。
在使用 Express.js 构建 RESTful API 之前,需要准备以下内容:
准备好这些条件后,即可开始使用 Express.js 构建 RESTful API。
aws-lambda-express-demo
文件夹并进入该目录: mkdir aws-lambda-express-demo
cd aws-lambda-express-demo
aws-lambda-express-demo
文件夹中创建一个文件 app.js
: touch app.js
npm
从注册表下载最新版本的 express
包,并将其存储在项目根目录的 node_modules
文件夹中。所有的包依赖项也将安装并存储在该文件夹中: npm install express
serverless-http
的中间件框架,这是一个用于创建无服务器应用程序的库。AWS Lambda 允许正常编写应用程序,然后将其包装在通过 HTTP 请求导出和执行的函数周围。serverless-http
也与 Azure、Google Cloud 等无服务器提供商兼容: npm install serverless-http
如果需要,可以通过以下命令全局安装 serverless-http
: npm install -g serverless-http
以下是使用 Node.js 实现 GET
、POST
、DELETE
和 PUT
方法的 Express.js 框架实现的 RESTful API 示例:
const express = require('express');
const app = express();
const serverless = require('serverless-http');
const users = [
{ id: 1, name: 'John', company: "ABC Company" },
{ id: 2, name: 'Frank', company: "XYZ Inc." },
{ id: 3, name: 'Ashley', company: "123 Company" },
];
app.use(express.json());
app.get('/users', (req, res) => {
res.json(users);
});
app.get('/users/:id', (req, res) => {
const user = users.find(user => user.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: 'User not found' });
res.json(user);
});
app.post('/users', (req, res) => {
const user = {
id: users.length + 1,
name: req.body.name,
company: req.body.company,
};
users.push(user);
res.json(user);
});
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex(user => user.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).json({ message: 'User not found' });
users.splice(userIndex, 1);
res.json({ message: 'User deleted' });
});
app.put('/users/:id', (req, res) => {
let user = users.find(user => user.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: 'User not found' });
user.name = req.body.name;
user.company = req.body.company;
res.json(user);
});
const handler = serverless(app);
const startServer = async () => {
app.listen(3000, () => {
console.log("listening on port 3000!");
});
};
startServer();
module.exports.handler = (event, context, callback) => {
const response = handler(event, context, callback);
return response;
};
上述代码创建了一个 Express.js 应用程序,并为 GET
、POST
、DELETE
和 PUT
方法添加了路由。应用程序使用内存中的 users
数组来存储数据,并使用 find
和 findIndex
方法根据 URL 中提供的 ID 检索和更新用户。需要注意的是,对于 POST
和 PUT
路由,需要解析请求正文,这可以通过 express.json()
中间件来完成。
在代码的末尾,startServer
函数启动了本地服务器,而 module.exports.handler
函数将 Lambda 事件处理程序与 Express 应用程序连接起来。
通过运行以下命令来启动服务器:
node app.js
服务器启动后,API 将开始运行。可以使用 Postman 发送测试 HTTP 请求。向 localhost:3000/users
发送请求时,应该会看到 200 OK
状态代码。此测试不需要请求正文。