创建一个简单的node的express项目

1.确定好自己的项目目录,然后对下面代码进行项目初始化(生成项目依赖文件)

执行完npm init -y后,文件夹里会生成package.json文件,这是项目的核心配置文件,记录依赖和脚本

#初始化npm项目

npm init

2.安装 express mongoose 依赖

--save会把 Express 添加到package.jsondependencies中,确保其他人克隆项目后能安装相同依赖。

npm install express mongoose  --save

3.安装下图创建好对应文件夹及文件

4.根据以下代码填写对应文件中

//该文件为连接MongoDB 数据库的配置文件

// MongoDB 连接模块
const mongoose = require(‘mongoose’);
const config = require(‘./index’);

async function connect() {
  const uri = process.env.MONGO_URI || config.mongoUri;
  if (!uri) {
    throw new Error(‘MongoDB URI 未配置,请在 config/index.js 中设置 mongoUri 或通过环境变量 MONGO_URI 传入。’);
  }

  try {
    // 新版本的mongoose不再需要这些选项,已默认启用
    await mongoose.connect(uri);
    console.log(‘MongoDB 已连接’);
  } catch (err) {
    console.error(‘无法连接到 MongoDB:’, err);
    throw err;
  }
}

module.exports = {
  connect,
  mongoose
};
// 服务器配置文件

module.exports = {
    // 服务器端口号
    port: 4413,
    // 主机地址
    host: ‘localhost’,
    // 静态文件目录配置
    // MongoDB 连接字符串(使用远程MongoDB)
    mongoUri: ‘mongodb数据库的连接地址’
};
//项目配置地中间件,注册api等

const express = require(‘express’);
const app = express();

//写一个get的api
app.get(‘/’, (req, res) => {
  res.send(‘这是node项目’);
});

module.exports = app;
const app = require(“./app”)
const config = require(‘./config’);
const MongoDB = require(“./config/db”)

const PORT = config.port || 4411;

// 连接数据库并启动服务器
MongoDB.connect().then(() => {
    console.log(‘MongoDB 已连接’);
   
    // 启动服务器
    const server = app.listen(PORT, () => {
        console.log(`服务器运行在 http://localhost:${PORT}`);
    });
   
    // 添加错误监听器,处理服务器启动错误
    server.on(‘error’, function(err) {
        console.log(‘服务器启动错误:’);
        if (err.code === ‘EADDRINUSE’) {
            console.log(‘ – 错误代码: EADDRINUSE’);
            console.log(` – 错误描述: 端口${PORT}已被占用`);
            console.log(‘ – 解决方法: 请关闭占用该端口的应用或修改服务器端口’);
        } else {
            console.log(‘ – 错误代码:’, err.code);
            console.log(‘ – 错误信息:’, err.message);
        }
        process.exit(1);
    });
}).catch(err => {
    console.error(‘无法连接到 MongoDB:’, err);
    process.exit(1);
});

// 处理未捕获的异常
process.on(‘uncaughtException’, (error) => {
    console.error(‘未捕获的异常:’, error);
    process.exit(1);
});

// 处理Promise rejection
process.on(‘unhandledRejection’, (reason, promise) => {
    console.error(‘未处理的Promise rejection:’, reason);
});

module.exports = null; // server 在成功连接后才会创建并监听

5.查看依赖文件package.json,修改启动文件(server.js)

将”main”设置为”server.js”

{
  "name": "allapi",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^5.2.1",
    "mongoose": "^9.1.5"
  }
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇