阅读量:1
在Ubuntu中利用Node.js开发API可按以下步骤进行:
-
安装Node.js和npm
- 使用NodeSource仓库安装(推荐):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - sudo apt install -y nodejs - 或使用nvm管理多版本:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc nvm install --lts
验证安装:
node -v和npm -v。 - 使用NodeSource仓库安装(推荐):
-
创建项目并初始化
mkdir my-api cd my-api npm init -y -
安装Express框架
npm install express --save -
编写API代码
创建server.js文件,示例代码(含GET/POST接口):const express = require('express'); const app = express(); const port = 3000; // 解析JSON请求体 app.use(express.json()); // GET接口示例 app.get('/api/hello', (req, res) => { res.json({ message: 'Hello, World!' }); }); // POST接口示例 app.post('/api/greet', (req, res) => { const { name = 'Guest' } = req.body; res.json({ message: `Hello, ${name}!` }); }); // 启动服务器 app.listen(port, () => { console.log(`API running at http://localhost:${port}`); }); -
运行和测试API
- 启动服务器:
node server.js - 测试工具:
- 浏览器访问
http://localhost:3000/api/hello - Postman/
curl测试POST接口(如curl -X POST -H "Content-Type: application/json" -d '{"name":"Alice"}' http://localhost:3000/api/greet)
- 浏览器访问
- 启动服务器:
-
生产环境优化(可选)
- 使用
pm2管理进程:npm install pm2 -g,然后pm2 start server.js - 添加错误处理、日志记录和数据库集成(如MongoDB/MySQL)。
- 使用
以上步骤基于Express框架快速搭建API,可根据需求扩展路由、中间件及功能模块。
以上就是关于“如何在Ubuntu中利用Node.js开发API”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm