使用Chatkit API,当在我的本地机器上运行React应用程序时,似乎一切正常,但当我将它推送到Heroku时,每次它试图通过服务器执行POST请求时,它都会给出Failed to load resource: net::ERR_CONNECTION_REFUSED I+m index.js:1375 error TypeError: Failed to fetch
这是我的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请求以创建新用户,并做出反应以加载新组件,但它只是停留在UsernameForm组件中,并且在控制台中我可以看到以下错误:
无法加载资源: net::ERR_CONNECTION_REFUSED index.js:1375错误TypeError:无法获取
发布于 2019-07-08 04:37:10
问题可能出在onUsernameSubmitted端点的localhost上。我们需要更多关于如何部署您的应用程序以及如何设计服务器和spa之间的通信的详细信息。如果你有一个Nginx,你可以在那里设置重定向。
发布于 2021-02-07 21:49:32
我看到了错误的三个潜在原因:
1),则确保graphql路径指向服务器url my-app.herokuapp.com而不是localhost:<port>,最简单的检查方法是通过浏览器/开发工具/网络vars我使用ApolloClient,而我的规则process?.env?.NODE_ENV ? 'prod_url' : 'dev_url'不起作用,因为在webpack中缺少vars定义:<代码>G211
new DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),```https://stackoverflow.com/questions/56925724
复制相似问题