vue,express连接postgresql数据库
时间: 2023-07-03 12:06:04 浏览: 63
要连接 PostgreSQL 数据库,你需要安装相应的 Node.js 驱动程序。我们推荐使用 `pg` 驱动程序,它是最流行的 PostgreSQL 驱动程序之一。
1. 安装 `pg`:
```bash
npm install pg
```
2. 在 Express 中使用 `pg`:
```javascript
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_user',
host: 'your_host',
database: 'your_database',
password: 'your_password',
port: 5432,
});
// 查询数据
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res);
pool.end();
});
```
3. 在 Vue 中使用 Express:
```javascript
// 在 Vue 中使用 Axios 或 Fetch 等工具发送请求
// 例如使用 Axios:
axios.get('/api/data').then((response) => {
console.log(response.data);
});
```
4. 在 Express 中处理请求:
```javascript
const express = require('express');
const app = express();
// 处理跨域请求
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// 处理数据请求
app.get('/api/data', (req, res) => {
pool.query('SELECT * FROM your_table', (err, result) => {
if (err) {
console.log(err);
res.status(500).send('Error fetching data from database');
} else {
res.send(result.rows);
}
});
});
// 启动 Express 服务
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
这就是连接 PostgreSQL 数据库的基本步骤。你可以根据自己的需要进行更改和扩展,例如使用 ORM 框架、添加身份验证等。