0

I+m playing with the Chatkit API, and when running a React app in my local machine everything seems to work fine, but when I pushed it to Heroku, every time it tries to do a POST request through the server, it gives Failed to load resource: net::ERR_CONNECTION_REFUSED and index.js:1375 error TypeError: Failed to fetch

This is my 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}`)
  }
})

And then this is my 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

I believe that it's at this time that it breaks

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

When submitting it is expected to make a POST request to create a new user, and React to load the new component, but it just stays in the UsernameForm component, and in the console I can see these errors:

Failed to load resource: net::ERR_CONNECTION_REFUSED index.js:1375 error TypeError: Failed to fetch

2 Answers2

1

Probably the issue is the localhost in the endpoint at onUsernameSubmitted. We need more details about how your application is deployed and how the communication between server and spa is designed. If you have an Nginx you can set the redirect there.

0

I see three potential reasons of the error:

  1. Database has to be well deployed and db:migrate triggered to define the db schema.
  2. If 1) is fulfilled, then make sure whether your graphql path points to server url my-app.herokuapp.com not to localhost:<port>, The easiest way to check that is via browser/devtools/network query.
  3. (optional) I use ApolloClient and my rule process?.env?.NODE_ENV ? 'prod_url' : 'dev_url' didn't work because of missing vars definitions in webpack:
new DefinePlugin({
    'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
    },
}),```
HGZdev
  • 1
  • 2