CentOS 宝塔面板使用nodejs连接mysql
经过两天的折腾,终于成功将nodejs连接上数据库,本文章将配置的过程写出来,用于本人总结或者其他需要的人参考。
本人的服务器环境
- 阿里云服务器,运行CentOs系统
- 宝塔面板
配置nginx
- 修改nodejs默认端口,直接监听 80 端口
- 使用 nginx 反向代理 nodejs 的 3000 端口,nginx监听 80 端口,当然 nginx 还有很多的用处
- 使用 其他 方法
本人 选择的是 第二种 使用nginx 反向代理。
- 安装
直接在宝塔面板的-软件商店-应用搜索-nginx,点击“安装”即可 - 配置
在 首页 点击 nginx 的 配置修改(没有放主页的话就找到nginx的配置文件)
在 http{} 中新插入一行服务配置,如下图(注意是插入,而不是改其他服务的配置)。
```javascript
http
{
# 无关的代码被我注释掉了
# ....
# ....
server { #博客项目
listen 80;
server_name xxx.com; #绑定的域名,就是你要操作的域名
location / # 访问 / 访问根目录,连接的是nodejs的服务
{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:3000; #对应该的Nodejs程序端口
}
}
# ...
# ...
}
nginx连接nodejs
参考网上教程,(注意:不能在window上解压再上传centos上,否则运行不了,因为window解压和Linux是不一样的)
- 在文件夹下建一个文件 test.js,写入以下内容
const http = require('http')
const server = http.createServer((req, res) => {
res.end('hello -- winter') //游览器打印
})
server.listen(3000, () => { //监听
console.log('listening on 3000 port')
})
- 打开终端运行:node test.js
node test.js
- 控制台打印
- 游览器返回
到这一步就可以说明nginx的配置和nodejs的安装没有问题。
nodejs连接数据库
数据库
- 安装 mysql 数据库 以及 创建 数据库
2. 在数据库中随便添加点内容
nodejs 连接数据库
- 使用 npm install mysql 安装数据库
- 创建 index.js 写入以下内容:
// nodejs 连接mysql
const mysql = require('mysql')
// 创建连接对象
const con = mysql.createConnection({
host: 'localhost',
user: 'myblog',
password: '你的数据库密码',
port: 3306,
database: 'myblog'
})
// 开始连接
con.connect()
// 执行 mysql 语句
// 查询列表
const sql = 'select * from blogs;'
// 更新数据
// const sql = `update users set realname = 'A' where id = '1';`
con.query(sql, (err, result) => {
if(err) {
console.log(err)
return
}
console.log(result)
})
// 关闭连接
con.end()
- 使用 node index.js 运行 ,控制台返回