首页 > 解决方案 > Heroku 上的 React 应用程序无法发出 POST 请求

问题描述

我正在使用 Chatkit API,当在我的本地机器上运行 React 应用程序时,一切似乎都运行良好,但是当我将它推送到 Heroku 时,每次它尝试通过服务器发出 POST 请求时,它都会失败加载资源:net::ERR_CONNECTION_REFUSED 和 index.js:1375 错误类型错误:无法获取

这是我的 server.js

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const Chatkit = require('@pusher/chatkit-server')

const app = express()

const chatkit = new Chatkit.default({
    instanceLocator: I HAVE MY INSTANCE LOCATOR HERE,
    key: I HAVE MY KEY HERE,
  })

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())

app.post('/users', (req, res) => {
    const { username } = req.body
    chatkit
      .createUser({
        id: username,
        name: username
      })
      .then(() => res.sendStatus(201))
      .catch(error => {
        if (error.error === 'services/chatkit/user_already_exists') {
          res.sendStatus(200)
        } else {
          res.status(error.status).json(error)
        }
      })
  })

  app.post('/authenticate', (req, res) => {
    const authData = chatkit.authenticate({ userId: req.query.user_id })
    res.status(authData.status).send(authData.body)
  })

const PORT = 3001
app.listen(PORT, err => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Running on port ${PORT}`)
  }
})

然后这是我的 App.js

import React, { Component } from 'react'
import UsernameForm from './components/UsernameForm'
import ChatScreen from './ChatScreen'

class App extends Component {
  constructor() {
    super()
    this.state = {
      currentUsername: '',
     currentScreen: 'WhatIsYourUsernameScreen'
    }
    this.onUsernameSubmitted = this.onUsernameSubmitted.bind(this)
 }

  onUsernameSubmitted(username) {
    fetch('http://localhost:3001/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username }),
    })
      .then(response => {
        this.setState({
          currentUsername: username,
         currentScreen: 'ChatScreen'
        })
      })
      .catch(error => console.error('error', error))
  }

 render() {
    if (this.state.currentScreen === 'WhatIsYourUsernameScreen') {
      return <UsernameForm onSubmit={this.onUsernameSubmitted} />
    }
    if (this.state.currentScreen === 'ChatScreen') {
      return <ChatScreen currentUsername={this.state.currentUsername} />
    }
  }
}

export default App

我相信它就是在这个时候打破

return <UsernameForm onSubmit={this.onUsernameSubmitted} />

提交时预计会发出 POST 请求以创建新用户,并通过 React 加载新组件,但它只停留在 UsernameForm 组件中,并且在控制台中我可以看到以下错误:

加载资源失败:net::ERR_CONNECTION_REFUSED index.js:1375 error TypeError: Failed to fetch

标签: node.jsreactjsexpressherokuchatkit

解决方案


可能问题出localhost在端点中onUsernameSubmitted。我们需要有关如何部署应用程序以及如何设计服务器和 spa 之间的通信的更多详细信息。如果你有 Nginx,你可以在那里设置重定向。


推荐阅读