node.js - 如何使用api从数据库中获取数据?

标签 node.js reactjs sequelize.js sequelize-cli

我是 nodejs 和 reactjs 的初学者,我从 reactjs 和 nodejs 开发了一个应用程序,我使用 postgresql 作为数据库,当我尝试通过在 server.js 中调用 api 来获取员工详细信息时,它在 VScode 控制台中显示数据日志,但是 如果我在我的浏览器的开发者控制台中看到,没有从数据库中获取的数据 ,有人帮我解决这个问题吗?
server.js


    var restify=require('restify')
    const {empdetails,empdetails_id } = require('./Function');
    var server=restify.createServer() //server created
    
    server.get('/empdetails',empdetails)
    server.get('/empdetails_id/:id',empdetails_id)
    
    server.listen(8080, function(){
        console.log("server started...")
    })

function.js

    var Sequelize=require('sequelize')
    
    const connection = new Sequelize('mydb', 'postgres', '123456', {
        host: 'localhost',
        dialect:  'postgres' 
      });
    
      var Emp=connection.define('emp',{
        fullName: {
            type: Sequelize.STRING
          },
          email: {
            type: Sequelize.STRING
          }    
    })
    
    module.exports ={
    
       
    // employee details fetched
        empdetails: function empdetails(req,res,next){
            // res.send('employee details ')
            connection.sync().then(function(){
                Emp.findAll().then(function(emps){
                              console.log(emps)
                              var sample=emps
                              console.log(sample)
                              res.send(emps);
                  })
              })
        },
    // employee details by ID
        empdetails_id: function empdetails_id(req,res,next){
            res.send('employee details of :  '+req.params.id)
            connection.sync().then(function(){
                Emp.findByPk(req.params.id).then(function(emps){
                              console.log(emps)
                  })
              })
        },
        
     };

最佳答案

对不起,我不使用restify和sequelize。但是要进行简单的 API 调用,您可以使用 fetch:

fetch('urlToFetch').then(res => {
    if(res.ok) {
        console.log(res.json())
    } 
    else {
        console.log('Error')
    }
})
.catch(error => {
    console.log('Error: ' + error.message)
})
文档:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

关于node.js - 如何使用api从数据库中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63169285/

相关文章:

node.js - 使用目标特定代码创建 npm 模块

javascript - 警告 : setState(…): Cannot update during an existing state transition

node.js - 如何使用 "Blank Node.js"模板在 Visual Studio 2019 中调试 React 应用程序

sql - Sequelize : Tables aren't associating properly

node.js - NodeJS Sequelize ORM db :seed:all drops tables from db

javascript - 将选定的日期与表列或 MySQL 查询生成的日期数组进行比较

node.js - 设置 "firebase javascript"与 "ionic serve"一起使用

javascript - 使用node.js/express保存数据到mysql,无需刷新页面

javascript - 类型错误 : Super expression must either be null or a function, 未定义

postgresql - ORM/查询生成器库连接池大小和 pgbouncer 连接池大小有什么区别?