在Debian上使用Node.js进行API开发的步骤如下:
sudo apt update
sudo apt install nodejs npm
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
node -v
npm -v
mkdir my-api-project
cd my-api-project
npm init -y
这会生成一个package.json
文件,其中包含项目的元数据和依赖信息。
npm install express body-parser
index.js
文件,并编写你的API服务器代码。以下是一个简单的Express API示例:const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// 使用body-parser中间件来解析JSON请求体
app.use(bodyParser.json());
// 定义一个简单的GET路由
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello, World!' });
});
// 启动服务器
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
node index.js
http://localhost:3000/api/hello
应该会返回:{ "message": "Hello, World!" }
npm install pm2 -g
pm2 start index.js --name my-api
这样,你的API将会在生产环境中持续运行,并且PM2会自动处理崩溃和重启等问题。