javascript - Express/React 承诺停滞不前
问题描述
我在端口 5000 上有一个 Express 后端服务器,并对在端口 3000 上运行的前端做出反应。我正在尝试从快递路线中获取一些数据并将其返回到前端,但我的 Promise 永远不会解决。它总是以“停滞不前”而告终。
util.inspect(messageList) 在服务器控制台上显示我的数组,但我在前端的 Promise 永远不会解决。
我在 ComponentDidMount 上获取一些数据服务器端,如下所示:
class Conversation extends React.Component {
state = {
conversations: [],
messages: [],
error: null,
loading: true,
input: '',
owner: 'Unassigned'
}
componentDidMount() {
const { match } = this.props
const { conversationId } = match.params
// Make a POST request to our server and pass the conversationId
this.getMessages(conversationId)
}
getMessages(conversationId) {
return fetch('/search-conversation', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ conversation: conversationId })
})
.then(res => res.json())
.then((messages) => this.setState({ messages }))
}
服务器端:
app.post('/search-conversation', (req, res) => {
conversationId = req.body.conversation
if (!conversationId) {
res.send('/error');
} else {
console.log(`Success, conv id is ${conversationId}`);
}
// call function to go get messages from API
console.log(`fetching messages for ${conversationId}`)
return fetch(endpoint)
.then((res) => res.json())
.then(({ data }) => data)
.then((data) => {
const messageList = data[0].messages.data
return messageList
})
.then((messageList) => console.log(util.inspect(messageList)))
.catch(error => console.error(`Error: ${error}`))
});
任何想法表示赞赏,在此先感谢。
解决方案
您在服务器端缺少res.json()调用,它将向客户端发送响应:
app.post('/search-conversation', (req, res) => {
conversationId = req.body.conversation
if (!conversationId) {
res.send('/error');
} else {
console.log(`Success, conv id is ${conversationId}`);
}
// call function to go get messages from API
console.log(`fetching messages for ${conversationId}`)
return fetch(endpoint)
.then((res) => res.json())
.then(({ data }) => data)
.then((data) => {
const messageList = data[0].messages.data
res.json(messageList) // <-- sending response
})
.catch(error => console.error(`Error: ${error}`))
});
推荐阅读
- android - TypeError:admin.messaging.sendToTopic 不是函数
- git - Visual Studio 大规模 Git 存储库
- c# - 带有枚举下拉菜单的 Unity 自定义检查器
- c# - C# 中 USB 3.0 端口的实时信号图?
- mysql - 为我的案例构建模式数据库的最佳实践
- laravel - Laravel 属性转换
- sequence - 从上一个滴答中学习并在下一个滴答中改变行为
- c# - 邮件合并不保存c#
- sql-server-2012 - 更新外键表列
- azure-resource-manager - ARM 模板 - 映射不同资源组的应用程序洞察力/应用程序服务计划