如何使用pg-promises从快速后端查询带有查询数据的redux存储

问题描述 投票:0回答:1

我正在处理的项目的开发人员只剩下部分完成的前端和后端,现在我正在尝试将Node / Express后端连接到React / Redux前端,以便及时完成项目截止日期。

该应用程序有一系列具有类别值的下拉菜单(即医疗保健,咨询等),一旦他们全部被选中并提交,将使用所述输入查询Postgres数据库以返回满足用户的所有相关结果一系列卡片中的标准给用户。

剩下的主要问题(我使用Redux dev工具确定)是,尽管查询成功完成,但操作不会更新状态的“数据”属性(应该包含查询的服务数组)。

我已经包含了更新状态的reducer的代码,以及后端server.js文件中的相关请求。

Reducer.js

const leftSidebarReducer = (state = initialState, action ) => {
    async function categoryQuery(json)
        await fetch('/category_query', { //post request in Server.js
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
            },
            body: json //currently returns the user inputs
        })
        .then(function(response){
            return response.json(); //**Data I want in store here**
        })
        .catch(err => console.log(err));
    }

//--- Further down in the Reducer:  ---//

case actionTypes.QUERY_DB:
   var newdata = [];
   var testStr = JSON.stringify({
      cat: state.leftMenu.catDrop,
      subCat: state.leftMenu.subCatDrop,
      insCat: state.leftMenu.insDrop,
      langCat: state.leftMenu.langDrop,
    }); 
    categoryQuery(testStr) //Run the async function above with state values
    return {
       ...state,
       data: newdata //Where the data should be updating ***
    }

Server.js

app.post('/category_query', (req, res) => { //this is the main category query
  console.log(req); //this is an attempt to see if we receive the reqs
  db.any(
  `SELECT * FROM med_services
      WHERE cat_name = $1 AND subCat = $2 AND insurance = $3`
      ,['Medical Care', 'clinic', 'blue-cross']
       //normally would be [req.body.cat, req.body.subCat, req.body.insCat]
   )
    .then(data => {
        console.log('DATA:', data); // print data;
        res.send(data);
        console.log('category query sent successfully')
    })
    .catch(error => {
        res.send('Error processing query');
    })
});

这里的主要问题是,当reducer设置data: newData时,我会接收一个空数组(即data: [])而不是数据库中的值数组。

另一个问题实际上是将请求体传递给pg-promise(我现在只使用键入的字符串值进行测试)。 WHERE cat_name = $1 AND subCat = $2 AND insurance = $3`,['Medical Care', 'clinic', 'blue-cross']当尝试[req.body.cat等]时,我无法从undefined中读取body的属性。

node.js reactjs express react-redux pg-promise
1个回答
1
投票

这里的主要问题是reducer设置数据的位置:newData,而是接收一个空数组(即data:[])而不是数据库中的值数组。

您应该记录正在执行的实际查询,以查看正在执行的内容以及没有返回数据的原因。为此,要么使用初始化选项query,要么使用pg-monitor

另一个问题实际上是将请求体传递给pg-promise(我现在只使用键入的字符串值进行测试)。 WHERE cat_name = $ 1 AND subCat = $ 2 AND insurance = $ 3`,['Medical Care','clinic','blue-cross']

pg-promise更好地使用Named Parameters查询格式:

db.any(
  `SELECT * FROM med_services
      WHERE cat_name = $/cat/ AND subCat = $/subCat/ AND insurance = $/insCat/`, req.body)
    .then(data => {...}

然而,在尝试[req.body.cat等]时,我无法从undefined中读取body的属性。

这告诉你,你的requndefined,不知何故,并试图访问body属性undefined抛出那种错误。

© www.soinside.com 2019 - 2024. All rights reserved.