node.js与express.js创建项目以及连接数据库

搭建项目

一、技术准备

node版本:16.16.0

二、安装node成功后,安装express,命令如下:

复制代码
npm install -g express

或者:

复制代码
npm install --location=global express

再安装express的命令工具:

复制代码
npm install --location=global express-generator

三、创建项目:myservice是自己起的项目名称

复制代码
express myservice

进入项目文件:

复制代码
cd myservice

安装依赖包:

复制代码
npm install

++安装依赖包有时候会超时,多次执行npm install就会安装完成++

启动项目:

复制代码
npm start

浏览器访问http://localhost:3000就会看到页面

连接数据库

安装数据库包:

复制代码
npm install mysql2

新建数据库配置文件config/dbconfig.js:

复制代码
const mysql = require('mysql2/promise');
// 创建数据库连接池

const pool = mysql.createPool({

host: '', // 主机名

port: 3306,

user: '', // 用户名

password: '', // 密码

database: '' // 数据库名称

});

module.exports = pool

新建api目录存放接口文件,新建api/test.js接口文件:

复制代码
const express = require("express");

const app = express();

const pool = require("../config/dbconfig");

app.get("/", async (req, res) => {

try {

const connection = await pool.getConnection(); // 从连接池获取连接对象

// 查询数据库操作

const [rows] = await connection.query("SELECT *FROM users");

// 返回结果

res.json(rows);

// 关闭连接

connection.release();

} catch (error) {

console.log(error);

res.status(500).send("Internal Server Error");

}

});

module.exports = app;

最后在入口文件app.js里引入(参考项目自带的两个路由引入方法):

复制代码
var testRouter = require('./api/test');

app.use('/test', testRouter);

每次修改保存后,需要重启项目才能生效!

重启后访问地址:http://localhost:3000/test,就可以看到数据库`users`表里的数据:

相关推荐
桃子不吃李子3 天前
简单搭建express服务器
运维·服务器·express
书中自有妍如玉4 天前
Node.Js Express Sqlite3 接口开发
node.js·express
showmethetime5 天前
使用 Node.js 和 Express 构建 RESTful API
node.js·restful·express
濮水大叔5 天前
VonaJS业务抽象层: 验证码体系
typescript·nodejs·nestjs
2501_938780287 天前
《Node.js 面试考点精讲:Express 生态与常见问题解决方案》
面试·node.js·express
2501_938790077 天前
《Node.js 面试避坑:Express 常见问题误区与正确答案解析》
面试·node.js·express
2501_938782099 天前
《Express 面试高频错题集:容易踩坑的 Node.js 后端问题解析》
面试·node.js·express
嘉年华-cocos9 天前
nodejs 使用speaker + ffmpeg 实现静默播放MP3
ffmpeg·nodejs·mp3
_光光11 天前
大文件上传服务实现(后端篇)
后端·node.js·express
濮水大叔12 天前
VonaJS AOP编程大杀器:外部切面
typescript·nodejs·nestjs