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.
Related
so the problem i'm having is, there is a directory in my public_html file named blog that is not related to my nextJs app, so basically after i deploy the app on host, everything works fine until i choose to check my blog part, for example the url below:
www.sth.com/blog
when i get there, i get the default next 404 page, the problem is, there is actual pages there, and i want my nodeJs server to ignore that exact route so when user goes to www.sth.com/blog, node app kind of ignore it and let it load the basic html pages.
i think it has something to do with my server.js file so here's the code in server.js
also i hosted the app on cpanel if that's important.
const { createServer } = require('http')
const next = require('next')
const isDevMode = process.env.NODE_ENV !== 'production'
const port = process.env.PORT ? process.env.PORT : 3000
const nextjsApp = next({ dev: isDevMode })
const nextjsRequestHandler = nextjsApp.getRequestHandler()
nextjsApp
.prepare()
.then(() => {
createServer((req, res) => {
const url = new URL(req.url, "http://w.w")
nextjsRequestHandler(req, res, url)
}).listen(port, (err) => {
if (err) throw err
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
thank you in advance.
In your server configuration you have to check if request is meant for next or not. If not - you need to respond with your page, instead of passing request further to next:
(req, res) => {
const url = new URL(req.url, "http://w.w");
if (/^\/blog\//.test(url.pathname)) {
// send response with blog
} else {
// pass everything to Next
nextjsRequestHandler(req, res, url);
}
};
Another option would be to split next and not next in two different parts and route requests to them through reverse proxy.
Recently I picked up Node.js + Express.js in order to pair them with Socket.io and make a real time chat application. The problem is that since I'm relatively inexperienced with Node.js and Express.js, I'm having some trouble figuring out where to put my logic and how to separate it in different files. Right now, the logic that creates my Socket.io namespaces is in the www file and I'm trying to figure out where to place it. Right now it looks like this:
www File:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
let io = require('socket.io')(server);
servers.forEach((server) => {
console.log(server.name)
io.of(server.endpoint).on('connection',(socket) => {
socket.on('messageToServer', (message) => {
let roomName = Object.keys(socket.rooms)[1]
let room = server.room.find((room) => {
return room.name == roomName
})
room.history.push(message)
io.of(server.endpoint).to(roomName).emit('messageToClient', message)
})
socket.on('joinRoom', (roomToJoin) => {
let roomToLeave = Object.keys(socket.rooms)[1]
socket.leave(roomToLeave)
socket.join(roomToJoin)
let room = server.room.find((room) => {
return room.name == roomToJoin
})
socket.emit('chatHistory', room.history)
})
})
});
What I tried is the following - I created a socket.js file and put it in a folder called utility, moved the code from www to the socket.js file and tried exporting the server from my www file to my socket.js file so that Socket.io can access it:
socket.js File:
let server = require('../bin/www').server
let io = require('socket.io')(server);
function createSocketServers() {
servers.forEach((server) => {
console.log(server.name)
io.of(server.endpoint).on('connection',(socket) => {
socket.on('messageToServer', (message) => {
let roomName = Object.keys(socket.rooms)[1]
let room = server.room.find((room) => {
return room.name == roomName
})
room.history.push(message)
io.of(server.endpoint).to(roomName).emit('messageToClient', message)
})
socket.on('joinRoom', (roomToJoin) => {
let roomToLeave = Object.keys(socket.rooms)[1]
socket.leave(roomToLeave)
socket.join(roomToJoin)
let room = server.room.find((room) => {
return room.name == roomToJoin
})
socket.emit('chatHistory', room.history)
})
})
});
}
module.exports = createSocketServers
www File:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
module.exports = server
require('../utility/socket').createSocketServers
As soon as I did that, my code stopped working, so I can only assume I haven't done it correctly, hence why I'm here asking for help. Thanks!
Everything looks fine except this line
require('../utility/socket').createSocketServers
When you do, module.exports = createSocketServers in socket.js file, you actually exporting the constructor.
If you run what you require, it should work;
require('../utility/socket')()
If you want to keep it like you do now, you have to export an object from socket.js file;
module.exports = { createSocketServers }
After exporting your module like above, you have to run it like below;
require('../utility/socket').createSocketServers()
Allright we are trying to make a chatbot, but we need it to recognize dutch language, this is the code we have so far, but we don't know how to add dutch language support. We already tried alot but we dont seem to get it working!
const builder = require('botbuilder');
const express = require('express');
const fs = require('fs');
const { Recognizer,LangNl } = require('node-nlp');
const modelName = './smalltalk.nlp';
const excelName = './smalltalk.xls';
// Creates a connector for the chatbot
const connector = new builder.ChatConnector({
appId: null,
appPassword: null,
});
// Creates a node-nlp recognizer for the bot
const recognizer = new Recognizer();
if (fs.existsSync(modelName)) {
recognizer.load(modelName);
} else {
recognizer.loadExcel(excelName);
recognizer.save(modelName);
}
// Creates the bot using a memory storage, with a main dialog that
// use the node-nlp recognizer to calculate the answer.
const bot = new builder.UniversalBot(connector, (session) => {
recognizer.nlpManager.addLanguage("nl","Nl","NL")
recognizer.recognize(session, (err, data) => {
session.send(data.answer || 'I don\'t understand');
session.endDialog();
});
}).set('storage', new builder.MemoryBotStorage());
recognizer.setBot(bot, false);
// Creates the express application
const app = express();
const port = process.env.PORT || 3000;
app.post('/api/messages', connector.listen());
app.listen(port);
console.log(`Chatbot listening on port ${port}`);
I have a Heroku app with Cloudflare and I try to display a different version according to the localization of the client.
It works well in developpment but it's not the case in production (the /en is always displayed, not the /fr).
I use the express-ip npm package.
The code:
const express = require('express');
const router = express.Router();
const expressip = require("express-ip");
router.use(expressip().getIpInfoMiddleware);
router.get("/", function ipFrance(req, res) {
const ipInfo = req.ipInfo;
const ipInfoRegion = req.ipInfo.region;
const ipInfoCountry = req.ipInfo.country;
//var message = `Hey, you are browsing from ${ipInfoRegion}, ${ipInfoCountry}`;
if(ipInfoCountry == "FR" || ipInfoRegion == "Wallonia") {
res.redirect("/fr");
} else {
res.redirect("/en");
}
});
module.exports = router;
Don't offer translations based on IP address. There's an HTTP header for that, and an express API method req.acceptsLanguages() which uses that header:
router.get("/", function (req, res) {
if (req.acceptsLanguages("fr")) {
res.redirect("/fr");
} else {
res.redirect("/en");
}
});
Some French-native people may like browsing in English, and other parts of the world may prefer to browse in French. Let them make that decision, don't make it for them.
I need to access my backend API to send info from a contact form for an email, I deployed my app in a webhost called Kinghost and it gave me two urls the first is generically mywebaddr.com:port-number and the second is mywebaddr.com/site.
I have tried to use both addresses with the function route in the end just like I did in localhost, that in order to work I used http://localhost:4000/contact for example, but it didn't work...
this is my request:
const baseUrl = 'http://mywebsiteurl.com/contact'
const initialState = {
message: {
name: '',
email: '',
subject: '',
main: ''
},
}
export default class ContactUs extends Component {
state = { ...initialState }
reset = () =>{
this.setState({message: initialState.message})
}
send = () => {
const message = this.state.message
const url = baseUrl
console.log(message)
axios.post(url, message)
.then(this.reset())
.then(alert('Message successfully sent!'))
}
this is my index.js (backend)
const express = require('express')
const app = express()
const consign = require('consign')
const port = 4005
consign()
.then('./config/middlewares.js')
.then('./api')
.then('./config/routes.js')
.into(app)
app.listen(port, () => {
console.log(port)
})
my middlewares.js contains cors
const bodyParser = require('body-parser')
const cors = require('cors')
module.exports = app => {
app.use(bodyParser.json())
app.use(cors())
}
Actually, I don't think it's because of my code itself once I can execute everything perfectly in localhost, but somehow I can't get through with the correct URL
I'm new to node and I can't guess what am I doing wrongly, so if someone can help me I'd be really thankful :)
This is not a question for stack-overflow as your issue is not with the application but is with your network.
Anyhow, your API application is running on port 4005. Make sure the port is open with your hosting provider. while your at it make sure your port 4000 is open as well.
after you confirm your firewall settings ill update my answer if your still facing issues.