NodeJS+express Insert data into table 多次
NodeJS+express Insert data into table multiple times
我是 nodeJs 新手。
我正在尝试制作一个简单的服务器(nodeJS + Postgres),每次使用参数调用 URL 时,它都会向数据库插入一个新行(基于 URL)。
问题是,以下代码在第一次调用 URL 时有效,但第二次调用时并没有在数据库中插入数据。
每次 URL 被调用时我如何让它工作?
谢谢
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const { Client } = require('pg');
const client = new Client({
connectionString: 'postgres://...........',
ssl: true,
});
app.get('/item/', (req, res) =>
(client.connect()
.then(()=>console.log('sucessful connection to DB'))
.then(()=>client.query(`INSERT INTO items(id,user) values('${req.query.id}','${req.query.user}')`))
.then(res.send("user sent"))
.catch(e=>console.log(e))
.finally(()=>client.end())))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
您正在重用客户端,您不能那样做。在你的情况下最好使用连接 pool.
const pool = new Pool({
connectionString: 'postgres://...........',
ssl: true,
})
app.get('/item/', (req, res, next) => {
pool.query('...')
.then(result => res.send('ok'))
.catch(next)
})
另外,不要连接这些值,否则您很容易受到 SQL 注入攻击。使用 parameterized query 代替
我是 nodeJs 新手。
我正在尝试制作一个简单的服务器(nodeJS + Postgres),每次使用参数调用 URL 时,它都会向数据库插入一个新行(基于 URL)。 问题是,以下代码在第一次调用 URL 时有效,但第二次调用时并没有在数据库中插入数据。
每次 URL 被调用时我如何让它工作?
谢谢
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const { Client } = require('pg');
const client = new Client({
connectionString: 'postgres://...........',
ssl: true,
});
app.get('/item/', (req, res) =>
(client.connect()
.then(()=>console.log('sucessful connection to DB'))
.then(()=>client.query(`INSERT INTO items(id,user) values('${req.query.id}','${req.query.user}')`))
.then(res.send("user sent"))
.catch(e=>console.log(e))
.finally(()=>client.end())))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
您正在重用客户端,您不能那样做。在你的情况下最好使用连接 pool.
const pool = new Pool({
connectionString: 'postgres://...........',
ssl: true,
})
app.get('/item/', (req, res, next) => {
pool.query('...')
.then(result => res.send('ok'))
.catch(next)
})
另外,不要连接这些值,否则您很容易受到 SQL 注入攻击。使用 parameterized query 代替