node.js - 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
解决方案
可能问题出localhost
在端点中onUsernameSubmitted
。我们需要有关如何部署应用程序以及如何设计服务器和 spa 之间的通信的更多详细信息。如果你有 Nginx,你可以在那里设置重定向。
推荐阅读
- jquery - 无法识别的表达式:输入[名称
- uml - 是否允许我们只为 1 个参与者(用户)使用用例图?
- java - 当负载均衡器位于 MQ 和应用程序之间时,负载均衡器会消耗消息吗?
- html - 自定义 HTML 预处理器/视图引擎
- c# - 如何在 C# 上向 datagridview 插入多行?
- graphql - Apollo Server 2 + Express:后处理程序中缺少 req.body
- angular - 动态表列和行 [Angular 6 + Bootstrap 3]
- python - 用于本地部署的 Docker 中的无服务器 AWS Lambda
- apache-spark - 如何在 SparkSQL 中合并小文件?
- python - 编译时没有名为“bs4”的模块错误