我是Node的新手,并且已经看过Net上的一些教程。我的主要问题是如何显示我创建的路线的结果。好吧,我正在使用控制台获取正确的数据,但是当我通过浏览器访问它时,它不显示json编码的数据。
这是我的product.js:
const express = require('express');
const router = express.Router();
const connection = require('../connection');
router.get('/',(req,res)=>{
res.send(products());
})
async function products(){
// console.log(products)
return await getProducts();
}
function getProducts(){
return new Promise((resolve,reject) =>{
connection.query('SELECT brand,description from products limit 100', function (err, rows, fields) {
if (err) throw err
resolve(JSON.stringify(rows))
})
})
}
module.exports = router;
这是控制台日志结果:http : //prntscr.com/llxgk2
这是邮递员的结果:http : //prntscr.com/llxgy3
您需要兑现承诺。在您的情况下,可能使用then
和catch
处理程序:
router.get('/',(req,res)=>{
products()
.then(products => {
res.json(products);
})
.catch(error => {
// ...send error response...
});
});
注意我曾经res.json
发送过响应。您可能希望将其更改resolve(JSON.stringify(rows))
为“ just” resolve(rows)
,并将处理行留给调用方。(res.json
将为您字符串化。)
您可能还会看到Koa,它与Express的开发人员相同,后者async
为路由功能提供了一流的支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句