【发布时间】:2018-12-18 07:11:21
【问题描述】:
我正在尝试在 firebase 上更新此文档,它第一次工作,但之后它给了我这个错误:
Error: Can't set headers after they are sent
这是切换值的按钮:
getActionButtons = () => {
if(this.state.stepIndex > 2){
return (<ActionButtons>
<ActionButton label={this.state.userType === 'Rider' ? this.state.available ? 'Found a carpool?' : 'look for carpool' : this.state.available ? 'Car is Full?' : 'Available for carpool'} primary={!this.state.available} secondary={this.state.available} onClick={() => {
console.log("eventId: ", this.props.eventId.event)
console.log("userId: ", firebase.auth().currentUser.uid)
// firebase.database().ref('/' + this.props.eventId.event + '/posts/' + firebase.auth().currentUser.uid).transaction((post => {
// if (post) {
// if (post.available) {
// post.available = !post.available
// } else {
// post.available = this.state.available
// }
// }
// return post;
// }))
firebase.database().ref('/' + this.props.eventId.event + '/posts/' + firebase.auth().currentUser.uid + '/available').set(!this.state.available)
this.setState({
available: !this.state.available
});
this.props.update();
}}/>
</ActionButtons>)
}
}
服务器代码:
const activeRoute = routes.find(route => matchPath(req.url, route)) || {}
const isEventPage = activeRoute.name === "carpoolingPage"
app.get("*", (req, res, next) => {
if(isEventPage) {
if (req.params[0]) {
let eventRef = firebase.database().ref(req.params[0])
eventRef.on("value", (snapshot) => {
const event = snapshot.val()
// console.log("event: ", event)
if(!event)
res.redirect("/eventnotfound")
else {
const { title, location, description } = event
const preloadedState = { currentEvent: event }
const store = configureStore(preloadedState)
const markup = generateMarkup(store)
res.send(HTML({
title: `Carpooling to ${ title }`,
markup, styleTags,
preloadedState,
ogTitle: `Carpooling to ${ title }`,
ogDescription: `Find people to carpool with to ${ title }. Choose to ride or drive to ${ location } ${ description === null ? '' : `Event Description: ${ description }`}`
}))
}
})
}
}
else {
const store = configureStore()
const markup = generateMarkup(store)
res.send(HTML({ markup, styleTags }))
}
})
我将 SSR 与 Node 和 React 一起使用,而 express 服务器仅使用 cors()。
仅供参考,它会在 firebase 上正确切换值,服务器退出并出现上述错误的问题导致其后面的代码无法运行。
顺便说一句,我尝试使用 firebase 事务并尝试删除 firebase 行之后的代码,但它给出了相同的错误。
我已经关注了关于堆栈溢出的所有类似问题,但它与我的问题不符。
【问题讨论】:
-
这个错误肯定来自 Express.js 代码。你能分享那条路线的代码吗?
-
您还有其他 API 调用吗?
-
能否检查一次错误。看看代码破坏了哪一行?
-
我不知道火力基地。但我确信
eventRef.on("value", ...)不止一次发生。并且您的res.redirect或res.send被多次调用。在快递中,如果您回复过一次,您将无法再次回复。希望这能解决您的问题。 -
太棒了。我已将其添加为答案
标签: node.js reactjs firebase firebase-realtime-database