在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會自動處理崩潰和重啟等問題。