ubuntu

Node.js在Ubuntu上如何进行API开发

小樊
46
2025-08-11 05:12:03
栏目: 编程语言

在Ubuntu上进行Node.js API开发,可按以下步骤操作:

  1. 安装Node.js和npm

    • 使用官方仓库安装(推荐LTS版本):
      sudo apt update  
      sudo apt install nodejs npm  
      
      验证安装:node -vnpm -v
    • 或使用nvm管理多版本:
      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash  
      source ~/.bashrc  
      nvm install --lts  
      ```。  
      
      
  2. 初始化项目

    mkdir my-api  
    cd my-api  
    npm init -y  
    ```。  
    
    
  3. 安装框架与依赖

    • 安装Express框架:
      npm install express  
      
    • 如需解析请求体、跨域等,安装额外中间件:
      npm install body-parser cors  
      ```。  
      
      
  4. 编写API代码

    • 创建app.js文件,示例代码(以RESTful API为例):
      const express = require('express');  
      const app = express();  
      app.use(express.json()); // 解析JSON请求体  
      
      // 示例路由:获取所有用户  
      app.get('/api/users', (req, res) => {  
        res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);  
      });  
      
      // 示例路由:创建用户  
      app.post('/api/users', (req, res) => {  
        const user = req.body;  
        res.status(201).json(user);  
      });  
      
      const PORT = 3000;  
      app.listen(PORT, () => {  
        console.log(`Server running on http://localhost:${PORT}`);  
      });  
      ```。  
      
      
  5. 运行与测试

    • 启动服务器:
      node app.js  
      ```。  
      
    • 使用工具测试:
      • 浏览器访问http://localhost:3000/api/users
      • 使用Postman或curl发送POST/GET请求:
        curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie"}' http://localhost:3000/api/users  
        ```。  
        
        
  6. 进阶开发

    • 数据库集成:使用MongoDB(Mongoose)、MySQL等存储数据。
    • 身份验证:添加JWT或OAuth中间件。
    • 生产环境部署:使用PM2管理进程、Nginx反向代理、环境变量配置(dotenv)。

参考资料:[1,2,3,4,5,6,7,8,9,10,11]

0
看了该问题的人还看了