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.
Related
I have a problem with my api. I want to use the firestore to input data for login & register with APi. Then, when i want to add the document database with user's input email when register but the output is error. my reasons for adding document with user's email is for easier for the next login step for its validation to compare the password also the email.
here the code that i already make:
const functions = require("firebase-functions");
const express = require("express");
// eslint-disable-next-line no-unused-vars
const cors = require("cors");
const admin = require("firebase-admin");
admin.initializeApp();
const app = express();
const db = admin.firestore();
app.post("/Register", (req, res) => {
const {
name,
email,
password,
phone,
} = req.body;
const saldo = 0;
const valAcc = db.collection("Users").doc(email);
valAcc.get().then((doc) => {
if (doc.exists) {
res.status(409).send("User Already Exist!");
}
});
db.collection("Users").doc(email).add({
Name: name,
Email: email,
Password: password,
Phone: phone,
Saldo: saldo,
});
res.status(201).send();
});
exports.apptest = functions.https.onRequest(app);
Do you guys have any solution? rly appriciate for any help.
I don't recommend handling user authentication yourself. I recommend using Firebase built-in tool for this instead: Firebase Authentication
With this, it's easy to implement email/passwords or providers (google, facebook etc) login.
And it's probably much safer than doing from scratch.
Afterwards you can use the UID or email of the logged user for storing/retrieving data on Firestore.
I've been having a strange issue where I've created a basic Nodejs API that I'm trying to host on Heroku which works perfectly from a local standpoint but as soon as I try to test through Heroku I get an authentication error when a MySQL connection is attempted.
From what I can see, when doing Postman tests, Heroku is adding information to my connection information which then causes authentication failure. Authentication to the API itself works but fails the MySQL connection.
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const utils = require('./utils');
const app = express();
const leadsdb = mysql.createPool({
host: "hostIP",
user: "username",
password: "password",
database: "database",
});
const port = process.env.PORT || 4000;
// enable CORS
app.use(cors());
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/register", (req, res) => {
const firstName = req.body.firstName
const lastName = req.body.lastName
const email = req.body.email
const number = req.body.number
const country = req.body.country
const age = req.body.age
const occupation = req.body.occupation
const sqlInsert = "INSERT INTO Leads (FirstName, LastName, Email, Country, Phone, Age, Occupation) VALUES (?,?,?,?,?,?,?)"
leadsdb.query(sqlInsert, [firstName, lastName, email, country, number, age, occupation], (err, result) => {
if(!result) {
res.send(err)
}
else {
res.send(result)
}
})
{
"code": "ER_ACCESS_DENIED_ERROR",
"errno": 1045,
"sqlMessage": "Access denied for user 'username'#'ec2-54-170-17-28.eu-west-1.compute.amazonaws.com' (using password: YES)",
"sqlState": "28000",
"fatal": true}
If I'm not mistaken, the '#'ec2-54-170-17-28.eu-west-1.compute.amazonaws.com' is not supposed to be included in the login information and it was not passed in where the DB connection is referenced.
I don't know if this is enough information so please ask for anything that may be needed. Appreciate any assistance.
I can see that you haven't specify the port. While connecting to a remote database from Heroku you should use these fields:
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'db_name',
insecureAuth: true
there is a one option also that you created a connection string like
DATABASE_URL=mysql2://username:password#ip.goes.here/data_base_name --app heroku-app-name
and specify it in your .env fil.
This makes the process lot more easier.
I realised that Hostgator has IP whitelisting rules for remote access to the hosted SQL servers. So Heroku wasn't appending anything to the connection, the server was actually responding saying the connection isn't allowed from the requesting hostname.
I appreciate all the help and I'm sorry for wasting the time of those who helped out.
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.
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