简体   繁体   中英

NodeJS deploying with Heroku

I am trying to upload my NodeJS project on Heroku. The project is a multiplayer game, locally the code works for me and both players enter the same map. But, in Heroku I don't get both players on the same map.

I leave the NODEJS code

const express = require("express")
const cors = require("cors")

const app = express()

app.use(express.static('public'))
app.use(cors())
app.use(express.json())

const jugadores = []

const PORT = process.env.PORT || 8080

class Jugador {
  constructor(id) {
    this.id = id
  }

  asignarMokepon(mokepon) {
    this.mokepon = mokepon
  }

  actualizarPosicion(x, y) {
    this.x = x
    this.y = y
  }

  asignarAtaques(ataques) {
    this.ataques = ataques
  }
}

class Mokepon {
  constructor(nombre) {
    this.nombre = nombre
  }
}

app.get("/unirse", (req, res) => {
  const id = `${Math.random()}`

  const jugador = new Jugador(id)

  jugadores.push(jugador)

  res.setHeader("Access-Control-Allow-Origin", "*")
  
  res.send(id)
})

app.post("/mokepon/:jugadorId", (req, res) => {
  const jugadorId = req.params.jugadorId || ""
  const nombre = req.body.mokepon || ""
  const mokepon = new Mokepon(nombre)
  
  const jugadorIndex = jugadores.findIndex((jugador) => jugadorId === jugador.id)

  if (jugadorIndex >= 0) {
    jugadores[jugadorIndex].asignarMokepon(mokepon)
  }
  
  console.log(jugadores)
  console.log(jugadorId)
  res.end()
})

app.listen(PORT, () => {
  console.log("Servidor funcionando", PORT)
})

I leave a small part of the code here because it is not possible to publish so much code. But I leave a link to the repository on GitHub

Link of the page hosted on Heroku: https://proyecto-mokepon.herokuapp.com/ Code link on GitHub: https://github.com/IamMatiasBazan/proyecto-mokepon

Locally it generates the random number for each player enter image description here

Deployed in Heroku I see this: enter image description here

The requests you are sending is pointed to localhost in your js file (multiple places, but this is one). Here you should consider changing it to be the heroku domain or just /mokepon/${jugadorId}/ataques (or something else).

It also looks like the app is sending a new request every 50ms, even if nothing happens. In this case I would then suggest you to look into socket.io to prevent the application to send useless request everytime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM