我正在编写一个应用程序,并且想使用节点模块
js-golden-hour
我不知道如何开始,但是我猜想,在我的React组件中,我应该使用类似的东西(我必须将zipCode传递给该模块) (反应GoldenHour.js)
state = {
postalCode: this.props.postalCode
};
componentWillMount(){
fetch('http://localhost:3001/goldenHour/', {
method: 'POST',
body: JSON.stringify({
postalCode: this.state.postalCode
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if( res.status === 200){
res.json()
.then( res => {
console.log(res.morning);
})
}else{
const error = new Error(res.error);
throw error;
}
})
.catch(err => {
console.log(err);
})
}
但这是我所能及的,我被卡住了。在我的节点api文件夹中,我创建了route并具有(goldenHours.js)
const express = require('express');
const router = express.Router();
const GoldenHourCalc = require('js-golden-hour');
router.post('/', (req, res, next) => {
if(res){
const goldenHour = new GoldenHourCalc(req.body.postalCode);
const morning = goldenHour.goldenHourMorning();
const evening = goldenHour.goldenHourEvening();
return res.status(200).json({
morningStart: morning.start,
morningEnd: morning.end,
eveningStart: evening.start,
eveningEnd: evening.end
});
}
});
module.exports = router;
我可以看到goldenHour正确接收了postalCode,但是当我尝试console.log在控制台中记录来自该请求的任何数据时,它只会显示“未定义”
答案 0 :(得分:0)
尝试将此api调用移至componentDidMount()
,从postman?
命中api也会得到正确的响应。如果将此作为中间件使用,则还需要调用{{1} }函数。