我已经按照https://node-postgres.com/guides/async-express上的node-postgres.org指令通过async
/ await
连接到我的postgres表users
。
导航到localhost:3000/users/1
将在浏览器中返回用户1的JSON字符串。我已经扩展了一点以返回localhost:3000/users
的所有用户。我的routes/user.js
脚本是:
const Router = require('express-promise-router')
const db = require('../db')
// create a new express-promise-router
// this has the same API as the normal express router except
// it allows you to use async functions as route handlers
const router = new Router()
// export our router to be mounted by the parent application
module.exports = router
router.get('/:id', async (req, res) => {
console.log('Where id = ');
const { id } = req.params
const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id])
res.send(rows[0])
})
router.get('/', async (req, res) => {
console.log('*');
const { rows } = await db.all('SELECT * FROM users')
res.send(rows)
})
在routes/index.js
这条路线的索引很简单:
const users = require('./user')
module.exports = (app) => {
app.use('/users', users)
}
我正在等待的db.query()
和db.all()
函数在db/index.js
:
const { Pool } = require('pg')
const pool = new Pool()
module.exports = {
query: (text, params) => pool.query(text, params),
all: (text) => pool.query(text)
}
我的主要app.js
文件中需要路由:
// ./app.js
const express = require('express')
const mountRoutes = require('./routes')
const cons = require('consolidate')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
mountRoutes(app)
// Assign Dust Engine to .dust files
app.engine('dust', cons.dust);
// Set .dust as the default extension
app.set('view engine', 'dust');
app.set('views', __dirname + '/views');
// Set Public Folder
app.use(express.static(path.join(__dirname, 'public')));
//Body parser and Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('/', function(reg, res) {
console.log('Root');
res.render('index', {hallo:'test'})
});
//Server
app.listen(3000, function() {
console.log('Server Started on Port 3000');
});
到目前为止,这个工作很漂亮!我得到了我想要的JSON字符串,我可以通过扩展我的路由和查询来构建这种API。
问题:如何将我的JSON对象rows
返回app.js
到res.render()
呢?
要么
我可以在我的应用中的任何地方做这样的事情:
jsonVar = GetMyJson('/users/1');
console.log(jsonVar);
收益:
[
{
"id": 1,
"usr_name": "Michael"
},
{
"id": 2,
"usr_name": "Thomas"
},
{
"id": 3,
"usr_name": "Paul"
}
]
然后,我可以将我想要的任何路径和参数传递到GetMyJson()
并处理生成的JSON。
对于javascript开发者来说这可能是一个微不足道的问题......
谢谢!
编辑21/12/2017
我创建了一个名为graphs.js
的前端脚本,当我调用功能api('/user/1')
时,它只记录我的结果。
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", api, false);
else if (el.attachEvent)
el.attachEvent('onclick', api);
var api = function(what){
// Action
sendRequest(what, function(result){
if(result){
log(result);
}
})
}
var apiEndpoint = 'http://localhost:3000/'
function sendRequest(_path, cb) {
var oReq = new XMLHttpRequest();
oReq.open('GET', apiEndpoint+_path);
oReq.onreadystatechange = function() {
if (this.readyState === 4) {
cb(JSON.parse(this.response));
}
else{
cb(null);
}
}
oReq.send();
}
function log(msg){
console.log(msg);
}
但这是在javascript中这样做的正确方法吗?
它的方法是这样的:
router.get('/', async (req, res) => {
console.log('*');
const { rows } = await db.all('SELECT * FROM users')
res.render('user', rows)
});
而不是res.send
你做res.render
你必须从database
得到它。进行自我呼叫不是一个理想的解决方案。所以你可以做到以下
const db = require('../db') // fix the location of db.js
app.get('/', function(req, res) {
db.all('SELECT * FROM users').then(function({ rows }) {
res.render('index', rows)
})
})
最好是制作一个userRepository.js
并在那里添加与db
相关的代码。然后在两个地方使用该存储库。