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
Related
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.
I am new to Node.js and trying to check if an e-mail is already taken by sending the email as a url parameter from iOS app. It is not working, not sure what I am doing wrong.
I am unable to console.log the email parameter in VSCode sent from the front-end, it DOES print in XCODE ( http://localhost:3000/api/user/email/test#gmail.com ) and I know the backend is getting the GET request.
My router code is:
const express = require(`express`)
const router = new express.Router()
const User = require(`../models/user-model`) // import User model
router.get(`/api/user/email/:email`, async (req, res) => {
console.log(req.params) // does NOT print email: test#gmail.com
try {
const user = await User.findOne(req.params.email)
if (user) {
console.log(user._id)
res.send({ available: false })
} else {
res.send({available: true})
}
} catch {
res.status(404).send()
}
})
Thank you!
const express = require(`express`)
const app = new express();
app.get(`/api/user/email/:email`, async (req, res) => {
console.log(req.params) // does NOT print email: test#gmail.com
try {
// const user = await User.findOne(req.params.email)
const user = {_id:123};
if (user) {
console.log(user._id)
res.send({ available: false })
} else {
res.send({available: true})
}
} catch {
res.status(404).send()
}
})
app.listen(3000,function(){
console.log("running");
})
Editing this.. I dont have enough points to comment.. your route seems to be fine, maybe you are not telling your application to use this route, somewhere before starting your application you should have something like:
this.app = new express();
...
this.app.use('/api', MailRouter); //<=== Adding your required mail route
...
I use to split url one parte here (/api) and the other one in the router (/user/email/:email). I'm not sure how to do it by adding it fully to the router (Maybe '/' maybe '')
I'm new in nodejs and I'm writing Viber-bot right now.
Viber-bot documentations is very bad and I really don't understand how to use some functions.
For example: I want to see some user's data, save that data on mobile device etc.
How can I use function:
bot.getUserDetails(userProfile)
I want to get name, id, phone number if it's possible and save it to some variables.
I have this code:
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const TextMessage = require('viber-bot').Message.Text;
const express = require('express');
const app = express();
if (!process.env.BOT_ACCOUNT_TOKEN) {
console.log('Could not find bot account token key.');
return;
}
if (!process.env.EXPOSE_URL) {
console.log('Could not find exposing url');
return;
}
const bot = new ViberBot({
authToken: process.env.BOT_ACCOUNT_TOKEN,
name: "I'm your bot",
avatar: ""
});
const port = process.env.PORT || 3000;
app.use("/viber/webhook", bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
Sorry if it's stupid questions.
Many thanks.
You can get the user profile data from the response triggered in these following events.
"conversation_started"
"message_received"
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot(logger, {
authToken: process.env.VB_API_KEY,
name: "Bot Name",
avatar: ""
});
bot.on(BotEvents.CONVERSATION_STARTED, (response) => {
const roomname = response.userProfile.id;
const username = response.userProfile.name;
const profile_pic = response.userProfile.avatar;
const country_origin = response.userProfile.country;
const language_origin = response.userProfile.language;
//Do something with user data
})
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
//Same as conversation started
});
If you want to fetch user info specifically, you can use this endpoint describe here in viber NodeJS developer documentation.
https://developers.viber.com/docs/all/#get_user_details
If you want to get bot info, try this endpoint.
https://developers.viber.com/docs/all/#get_account_info
I have been implementing a Next.js app for a side project of mine. It is a basic brochure-style site with a contact form.
The form works perfectly fine when the site is run locally, however I have just published the site to Netlify and now when submitting a form I encounter the following error:
POST https://dux.io/api/form 404
Uncaught (in promise) Error: Request failed with status code 404
at e.exports (contact.js:9)
at e.exports (contact.js:16)
at XMLHttpRequest.d.(/contact/anonymous function) (https://dux.io/_next/static/cFeeqtpSGmy3dLZAZZWRt/pages/contact.js:9:4271)
Any help would be extremely appreciated!
This is my Form Submit function:
async handleSubmit(e) {
e.preventDefault();
const { name, email, option, message } = this.state;
const form = await axios.post('/api/form', {
name,
email,
option,
message
});
this.setState(initialState);}
This is my server.js file:
const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const mailer = require('./mailer');
const compression = require('compression');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(compression());
server.use(bodyParser.json());
server.post('/api/form', (req, res) => {
const { email = '', name = '', option = '', message = '' } = req.body;
mailer({ email, name, option, text: message })
.then(() => {
console.log('success');
res.send('success');
})
.catch(error => {
console.log('failed', error);
res.send('badddd');
});
});
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, err => {
if (err) throw err;
console.log('> Read on http://localhost:3000');
});
});
It looks like nextjs tries to render the /api/form page and you get a not found with that.
Please make sure you start the server with node server.js instead of next start.
What about try to use full endpoint http://~~~/api/form instead of just /api/form?
Or I think, you can solve this problem if you use process.env
const config = {
endpoint: 'http://localhost:8080/api'
}
if (process.env.NODE_ENV === 'production') {
config.endpoint = 'hostname/api'
}
I am working on setting up Stampery. I am unable to figure out where to set the string API key in this API.JS file. The documentation says to set the STAMPERY_TOKEN as the API key not sure how to do this. Any help would be appreciated.
The link for Stampery is https://github.com/stampery/office.
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const Stampery = require('stampery');
const development = process.env.NODE_ENV !== 'production';
const stamperyToken = process.env.STAMPERY_TOKEN;
var proofsDict = {}
if (!stamperyToken) {
console.error('Environment variable STAMPERY_TOKEN must be set before running!');
process.exit(-1);
}
//var stampery = new Stampery(process.env.STAMPERY_TOKEN, development ? 'beta' : false);
// For now, always use production Stampery API due to not making it work against beta.
var stampery = new Stampery(process.env.STAMPERY_TOKEN);
router.use(bodyParser.json());
router.post('/stamp', function (req, res) {
var hash = req.body.hash;
// Throw error 400 if no hash
if (!hash)
return res.status(400).send({error: 'No Hash Specified'});
// Transform hash to upper case (Stampery backend preferes them this way)
hash = hash.toUpperCase()
// Throw error 422 if hash is malformed
var re = /^[A-F0-9]{64}$/;
if (!(re.test(hash)))
return res.status(422).send({error: 'Malformed Hash'});
stampery.stamp(hash, function(err, receipt) {
if (err)
res.status(503).send({error: err});
else
res.send({result: receipt.id, error: null});
});
});
router.get('/proofs/:hash', function (req, res) {
var hash = req.params.hash;
stampery.getByHash(hash, function(err, receipts) {
if (err)
res.status(503).send({error: err});
else
if (receipts.length > 0)
res.send({result: receipts[0], error: null});
else
res.status(200).send({error: 'Oops! This email has not yet been attested by any blockchain.'});
});
});
module.exports = router;
I have added the following in Azure website. Should this suffice :
You need to set up STAMPERY_TOKEN environment veriable before starting your server.
You can do this like this for example (in Windows) set STAMPERY_TOKEN=your-token&& node app.js
There are 2 ways to add this to environment (For Ubuntu).
Add to bashrc File. Like:
export STAMPERY_TOKEN="YOUR-TOKEN"
Pass these params before running server. Like:
STAMPERY_TOKEN=YOUR-TOKEN node server.js
To access this variable you can get by:
console.log(process.env["STAMPERY_TOKEN"]);