【发布时间】:2018-02-05 20:30:03
【问题描述】:
编辑:已通过切换到不同的 Android 手机模拟器解决此问题
我正在尝试创建一个简单的 React Native 应用程序,它首先会从 Express 后端获取一个 json 文件。
后端:
...data to be fetched up here in a dictionary
//Enable CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.get('/sightings', (req, res) => {
res.json(sightings);
});
app.post('/sightings', (req, res) => {
req.body.id = (sightings.length + 1).toString();
sightings.push(req.body);
res.json(req.body);
});
app.get('/species', (req, res) => {
res.json(species);
});
const port = process.env.PORT ? process.env.PORT : 8081;
const server = app.listen(port, () => {
console.log("Server listening port %s", port);
});
前端:
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
key: '',
sightings: [],
}
}
componentDidMount() {
fetch('http://10.0.0.2:3000/sightings')
.then(res => res.json())
.then(res => {
this.setState({sightings: res })
})
.catch((error) => {
console.log(error);
});
console.log(this.state.sightings);
}
显然这里的重点是使用数据更新状态中的目击事件,但它不起作用,我只返回了最初分配给 this.state.sightings 的空对象。
我是否缺少某些步骤?我是使用节点服务器的初学者,我遵循的各种教程就是这样。
【问题讨论】:
标签: javascript reactjs express react-native backend