Get client IP adress trough Heroku - javascript

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.

Related

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.

Why can't I connect to mongoDB atlas?

I am new in MongoDB, all my life I used MySQL.
I have created an account in atlas, set the IP to my IP and created a user and saved the password.
here is my code, why doesn't it work?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoPractice = require('./mongo');
const app = express();
app.use(bodyParser.json());
app.post('/products', mongoPractice.createProduct);
app.get('/products');
app.listen(3000);
and the mongo.js:
const MongoClient = require("mongodb").MongoClient;
const url =
"mongodb+srv://idan:<85IwoSzeQssHMzLN>#cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price,
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection("products").insertOne(newProduct);
} catch (error) {
return res.json(error);
}
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
the POSTMAN output:
Your ip may have changed, (check if the current ip address has information "(includes your current IP address)". For testing(!) you can add address 0.0.0.0/0 to the whitelist - it means every ip will be accepted - this solution is good for beginners
Firstly check you connection link from mongodb connect
Check username, password again
You can change password and try again
In mongo.js
You need to remove "< >" around the password.
const url = "mongodb+srv://idan:**85IwoSzeQssHMzLN**#cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
I encountered the same error once and I might have solution.
The most common one is that your IP address set to access the database might not match with your current IP address in which case you need to set it to your current IP or set to allow access from anywhere.
The issue which I had : If you have recently started using an ethernet cable try going back to wireless to access the mongoDB database from your backend script.

404 - File or directory not found in Next JS

I am making a next js application.
Deployment works fine in vercel.
For deploying the same project in another server, got help from https://stackoverflow.com/a/63660079/13270726 and used the same instructions in our app.
Deployed the out directory into server using ftp client.
Issue
-> When we enter into http://your-domain.com , it works fine. (Even page refresh also works fine in this page)
-> If we move to about page using the url, http://your-domain.com/about then it also works but on page refresh in the url http://your-domain.com/about results in the error,
-> This page refresh also results in the console error like,
Get http://your-domain.com/about Not found
next.config.js: (With public path)
const config = {
webpack: (config, { isServer }) => {
.
.
.
config.devServer = {
historyApiFallback: true
}
config.output.publicPath = "/"
return config;
}
}
module.exports = withPlugins(config);
The issue arises in page refresh only or when we manually type the url.. But while we navigate to it first time then the issue is not there.
Any good help would be much appreciated as I am stuck for long time..
Edit:
I have a server.js file and its code look like,
const dotenv = require("dotenv");
// import ENVs from ".env.local" and append to process
dotenv.config({ path: ".env.local" });
const express = require("express");
const address = require("address");
const chalk = require("chalk");
// create express web server instance
const app = express();
// pull out ENVs from process
const { LOCALHOST, PORT } = process.env;
// get the Local IP address
const LOCALIP = address.ip();
// tell express to serve up production assets from the out directory
app.use(express.static("out" + '/'));
app.get('/*', (req, res) => {
res.send('ok')
});
app.all('*', function(req, res) {
res.redirect('/index.html');
});
// tell express to listen for incoming connections on the specified PORT
app.listen(PORT, (err) => {
if (!err) {
// log the LOCALHOST and LOCALIP addresses where the app is running
console.log(
`\n${chalk.rgb(7, 54, 66).bgRgb(38, 139, 210)(" I ")} ${chalk.blue(
"Application is running at"
)} ${chalk.rgb(235, 220, 52).bold(LOCALHOST)} ${chalk.blue(
"or"
)} ${chalk.rgb(235, 220, 52).bold(`http://${LOCALIP}:${PORT}`)}\n`
);
} else {
console.err(`\nUnable to start server: ${err}`);
}
});

How to reach my backend API in a web host?

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.

request.ValidationErrors() is not a function() express and node js

I'm writing a chat application using MEAN stack. where I'm validating registration screen with express-validator package. Below is the source code of package inclusion in my server.js file. where I created a server.
let express = require('express');
let application = express();
let path = require('path');
let db = require("./db");
const server = require('http').createServer(application);
let bodyParser = require('body-parser');
let expressValidator = require('express-validator')
When a user clicks on register button. I will redirect the user to a registation controller where i'm having below piece of code.
`module.exports.RegisterUser = (req, res) => {
if (req.body) {
let user = new userModels(req.body);
req.check('username', 'Not a valid username').isEmail();
req.check('password', 'password doen\'t meet criteria').isAlpha();
var validationErrors = req.ValidationErrors();
if(validationErrors){
console.log(validationErrors.msg);
}
// if there is no validation error
user.save()
.then(user => {
return res.status(HttpStatus.CREATED).send("Sign up successfull");
})
.catch(err => {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err);
});
} else {
res.status(HttpStatus.BAD_REQUEST).send("Invalid Input");
}
}`
I can able to build the project but wasn't able to validate. I'm getting req.ValidationErrors() is not a function.
thanks in advance.
I believe it needs to be:
const validationErrors = req.validationErrors();
instead
EDIT: Whoops, just noticed Sterling Archer already posted with correct answer. Either way, I'll leave this here as reminder for all of us that don't read well

Categories

Resources