在Debian上利用Node.js進行Web開發是一個相對直接的過程,以下是一些詳細的步驟和建議:
sudo apt update
sudo apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
驗證安裝:
node -v
npm -v
mkdir my-web-app
cd my-web-app
npm init -y
這將創建一個package.json
文件,其中包含項目的元數據和依賴項。
npm install express --save
app.js
的文件,并添加以下代碼:const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
node app.js
現在,您可以在瀏覽器中訪問http://localhost:3000
,看到“Hello World!”的消息。
body-parser
來處理請求體:npm install body-parser --save
npm install ejs --save
在app.js
中配置模板引擎:
app.set('view engine', 'ejs');
app.set('views', './views');
創建一個views
目錄,并在其中創建一個index.ejs
文件:
<!DOCTYPE html>
<html>
<head>
<title>My Web App</title>
</head>
<body>
<h1>Welcome to My Web App</h1>
</body>
</html>
修改app.js
中的路由處理函數:
app.get('/', (req, res) => {
res.render('index');
});
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/your-repo.git
git push -u origin master
sudo npm install -g pm2
使用PM2啟動服務器:
pm2 start app.js
您可以使用以下命令管理PM2進程:
pm2 status
pm2 restart app.js
pm2 stop app.js
pm2 delete app.js
sudo apt install nginx
配置Nginx以將請求轉發到Node.js服務器:
sudo nano /etc/nginx/sites-available/default
在文件中添加以下內容:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
重啟Nginx:
sudo systemctl restart nginx
通過以上步驟,您可以在Debian上成功設置一個Node.js Web開發環境,并構建和部署一個簡單的Web應用程序。