node.js与express.js创建项目以及连接数据库
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
// 引入必要的模块
const express = require('express');
const mysql = require('mysql');
 
// 创建 Express 应用
const app = express();
 
// 设置 MySQL 连接配置
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'your_username',
  password : 'your_password',
  database : 'your_database'
});
 
// 连接到 MySQL 数据库
connection.connect(err => {
  if (err) throw err;
  console.log('Connected to the database.');
});
 
// 定义一个简单的 GET 路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});
 
// 监听3000端口
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});这段代码创建了一个简单的Express应用,并且展示了如何连接到MySQL数据库。它设置了一个基本的GET路由,并在控制台输出相应的连接信息。这是学习Node.js和Express.js初始步骤的一个很好的示例。
评论已关闭