jam*_*ggs 0 javascript fetch node.js promise reactjs
我在端口5000上有一个Express后端服务器,并响应在端口3000上运行的前端。我试图从Express Post路由中获取一些数据并将其返回到前端,但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 }))
}
Run Code Online (Sandbox Code Playgroud)
服务器端:
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}`))
});
Run Code Online (Sandbox Code Playgroud)
任何想法表示赞赏,在此先感谢。
您在服务器端缺少将响应发送到客户端的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}`))
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |