首页 分类三文章正文

Node.js与MySQL完美结合,轻松搭建高效网站

分类三 2024年10月02日 06:04 37 admin

随着互联网技术的不断发展,网站已经成为企业展示形象、拓展业务的重要平台,在众多技术中,Node.js以其高性能、轻量级的特点,成为了构建高效网站的首选,而MySQL作为一款高性能、开源的关系型数据库,更是与Node.js完美匹配,本文将详细介绍如何使用Node.js和MySQL搭建一个功能强大的网站。

环境准备

1、安装Node.js:从官网(https://nodejs.org/)下载并安装Node.js,确保环境变量配置正确。

2、安装MySQL:从官网(https://dev.mysql.com/downloads/installer/)下载并安装MySQL,确保环境变量配置正确。

3、安装Node.js包管理器npm:在Node.js安装过程中,npm会一同安装,无需额外安装。

搭建项目结构

创建一个名为“mywebsite”的文件夹,作为项目根目录,在根目录下,创建以下文件和文件夹:

mywebsite/
|-- node_modules/
|-- src/
|   |-- index.js
|   |-- db.js
|   |-- routes/
|       |-- index.js
|-- app.js
|-- package.json

配置数据库连接

1、在src/db.js文件中,编写MySQL连接代码:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'mywebsite'
});
connection.connect(err => {
  if (err) throw err;
  console.log('Connected to the MySQL server.');
});
module.exports = connection;

2、在package.json文件中,添加数据库连接依赖:

{
  "dependencies": {
    "mysql": "^2.18.1"
  }
}

编写业务逻辑

1、在src/routes/index.js文件中,编写网站首页的业务逻辑:

const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
  const connection = require('../db');
  connection.query('SELECT * FROM articles', (err, results) => {
    if (err) throw err;
    res.render('index', { articles: results });
  });
});
module.exports = router;

2、在src/index.js文件中,配置Express和路由:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.use('/', require('./src/routes/index'));
app.listen(port, () => {
  console.log(Server is running on http://localhost:${port});
});

3、在app.js文件中,引入src/index.js文件:

const index = require('./src/index');
module.exports = index;

创建静态资源

在public文件夹中,创建一个index.html文件作为网站首页:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>我的网站</title>
</head>
<body>
  <h1>欢迎来到我的网站</h1>
  <ul>
    {{ articles }}
  </ul>
</body>
</html>

运行项目

1、在命令行中,进入项目根目录。

2、运行命令:node app.js

3、打开浏览器,访问http://localhost:3000,即可看到网站首页。

通过以上步骤,您已经成功使用Node.js和MySQL搭建了一个简单的网站,在实际项目中,您可以根据需求添加更多功能,如用户认证、商品管理、订单处理等,Node.js和MySQL的强大性能,将为您的网站带来更好的用户体验。

不止是 “看新闻”,更是 “参与新闻”—— 在这里,你可以分享身边的真实故事,上海衡基裕网络科技有限公司 备案号:沪ICP备2023039794号 上海衡基裕网络科技有限公司发布内容仅供参考 如有侵权请联系删除QQ:597817868