【发布时间】:2019-01-21 15:01:38
【问题描述】:
我一直在尝试设置网站的后端,但在我使用 React 的前端尝试读取它时遇到问题。
设置:
- 我有一个包含属性(名称、价格、isBestSeller、isAvailable 等)的产品表。
- 我正在阅读此表并使用 NodeJS 将数据发送到前端,如下代码所示:
`
const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const knex = require('knex')
const database = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'username',
password : '',
database : 'databasename'
}
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
database.select('*').from('products').then(data => {
app.get('/', (req, res) => {
res.send(JSON.stringify(data));
});
});
app.listen(3001);
`
这很好用,如果我 console.log 它我会得到正确的数据。 问题出现在前端,因为我还不太熟悉 fetch 和 promises。
在介绍后端之前,我从一个简单的 .js 文件中读取产品,该文件包含如下对象数组:
export const productsContent = [
{
boxImage: 'https://i.imgur.com/dn9ty6l.png',
boxTitle: 'Arabusta Arabica',
boxPrice: '€15',
discountPrice: '€9.99',
bestSeller: false,
available: false,
description: 'Coming soon'
},
...
]
现在我用这个替换了上面的代码:
export const productsContent = [
fetch('http://localhost:3001')
.then(function(response) { return response.json(); })
.then(function(data) {
for (let i = 0; i < data.length; i++) {
productsContentArray.push(data);
}
})
];
我在这里尝试做的是从后端获取对象数组并将其推送到常量 productsContent 并使用它来显示产品。
不幸的是,在.fetch 之外,我得到了我不确定如何解析的承诺,当我在 fetch 内部进行控制台时,我得到了正确的值。
有谁知道我如何正确解决 fetch 的承诺或如何从 fetch 函数之外的数据中获取价值?
【问题讨论】: