【发布时间】:2021-04-02 04:26:52
【问题描述】:
我目前正在用 react js 构建一个 web 应用程序,并且偶然发现了 axios。我是 axios 的新手,对它的经验很少。到目前为止,我一直在使用从我的反应应用程序到我的节点/快速服务器的 http 请求的获取请求。目前我有我的节点服务器调用 MySQL 查询。这是获取请求:
app.get('/getAllBusinessAccountsTransactions', function(request, response) {
var {userID, accountID} = request.query;
const getAllBusinessAccountsTransactions = `CALL GetUniqueBusinessUniqueAccountTransactions('${userID}', '${accountID}')`;
mysqlConnection.query(getAllBusinessAccountsTransactions, (error, result) => {
if(error) {
console.log(error);
} else {
console.log('SUCCESSFULLY RETRIEVED THE TRANSACTIONS!!!');
var test = {result};
console.log({"test": test.result[0]});
response.status(200).send(
{"blah": test.result[0]}
)
}
})
})
这个获取请求似乎工作正常。当我用 console.log({"test": test.result[0]}); 打印出结果时这是我得到的回复:
{ test: [ RowDataPacket { TransactionID: 38, Date: '0000-00-00', Description: 'test', Debit: 50, Credit: 0, Connection: 'undefined', AccountID: 19 }, RowDataPacket { TransactionID: 39, Date: '0000-00-00', Description: 'test two', Debit: 50, Credit: 0, Connection: 'undefined', AccountID: 19 }, RowDataPacket { TransactionID: 40, Date: '0000-00-00', Description: 'a', Debit: 50, Credit: 0, Connection: 'undefined', AccountID: 19 } ] }
结果在我看来还不错。这是我在我的 react 应用中使用的 axios 函数来调用这个 get 请求。
getProducts () {
var accountIDValue = '19';
return axios.get('http://localhost:8080/getAllBusinessAccountsTransactions?userID=' + localStorage.getItem('currentUserID') + '&accountID=' + accountIDValue)
.then((response) => {
console.log('TEST MY NEW AXIOS');
console.log(response.data.blah);
})
}
再次,当我测试打印 axios 请求的结果时,我得到了预期的对象数组。现在这里是我怀疑我的错误来自哪里。下面是相关代码,我在其中调用了之前的axios函数:
const DataTableResponsiveDemo = () => {
const [products, setProducts] = useState([]);
const productService = new ProductService();
useEffect(() => {
console.log('GOLLY TESTING');
console.log(productService.getProducts());
productService.getProducts().then(blah => setProducts(blah));
}, []); // eslint-disable-line react-hooks/exhaustive-deps
我没有收到此代码的错误...这意味着我的网络应用程序不会崩溃。但是,我正在尝试使用此函数将数据设置为状态的数据填充表。但是,当我打印出使用 console.log(productService.getProducts()); 调用该函数的结果时;我在控制台中打印出这种奇怪的行为:
总而言之,我在节点获取请求中的查询检索了预期的数据。数据正确地发送到我的 axios 函数(至少在它从节点检索数据时打印它)。但是,当我调用 axios 函数时,我收到了这个奇怪的承诺待处理消息,并且我的对象数组不存在。这可能与我从节点获取请求发送数据的方式有关吗?如果这看起来像一个简单的问题,我深表歉意……就像我说的那样,我目前正在尝试了解 axios 并且很难弄清楚问题所在。非常感谢您的帮助!
【问题讨论】:
-
getProducts () { var accountIDValue = '19'; return axios.get('localhost:8080/getAllBusinessAccountsTransactions?userID=' + localStorage.getItem('currentUserID') + '&accountID=' + accountIDValue) .then((response) => { response.json() }).then(res => res ).catch(err => console.log(err.message) } 请试试这个,让我知道发生了什么
标签: javascript node.js reactjs http axios