javascript - Express/React promise 陷入停滞

标签 javascript node.js reactjs promise fetch

我在端口 5000 上有一个 Express 后端服务器,并在端口 3000 上运行 react 前端。我试图从 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 }))
  }

服务器端:

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}`))
});

关于javascript - Express/React promise 陷入停滞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57861306/

相关文章:

javascript - Bootstrap - 悬停时下拉菜单消失得太快

javascript - yield takeLatest 中类型 '"MY_EVENTS_LOAD "' is not assignable to parameter of type ' TakeableChannel<unknown>' 的参数

node.js - 捕获 Browserify 解析错误(独立选项)

javascript - 我应该在我的配置中向我的 appId 添加什么?

javascript - 从键盘写入 SVG 文本

JavaScript 性能 : While vs For Loops

javascript - 我怎样才能把这个 SVG ‘Sidebar Menu’ 放在右边?

javascript - 使用 Passport 本地身份验证注册在 Node.js 中不起作用

node.js - 作为 Slack 机器人回复丰富的消息

javascript - 单击类别时如何显示不同的项目列表