getting errors The POST method - js - javascript

what's the fault in this code
const express = require('express')
const app = express()
const port = 3000
var mysql = require('mysql');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('md5');
//MySQL Connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "school"
});
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); // support encoded bodies
app.get('/', (req,res) =>{
con.query("SELECT * FROM users", function(err, rows, fields){
if(err) throw err;
res.send("The first user is: " + rows[0].email);
});
});
app.post('/', function(req,res){
con.query("SELECT * FROM users WHERE name = ? AND password = ?" , [req.body.name, md5(req.body.password)] , function(err, result, fields){
if(err) throw err;
if(result.length > 0){
if(result)
res.send({ status:1, message: result});
} else{
res.send({ status:0, message: "error in username or password"});
}
});
});
app.listen(port, () => console.log('Example app listening at http://localhost:${port}'))
I get this error in cmd every time I use postman to try post:
Error: Illegal argument undefined
at module.exports (C:\\hsoub\\api\\node_modules\\md5\\md5.js:152:13)
at C:\\hsoub\\api\\index.js:50:87
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:144:13)
at Route.dispatch (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\route.js:114:3)
at Layer.handle \[as handle_request\] (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\layer.js:95:5)
at C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:284:15
at Function.process_params (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:346:12)
at next (C:\\hsoub\\api\\node_modules\\express\\lib\\router\\index.js:280:10)
at urlencodedParser (C:\\hsoub\\api\\node_modules\\body-parser\\lib\\types\\urlencoded.js:100:7)
what's the problem?

Related

How to handle timeout(--ms-- message) in nodejs

This photo shows --ms-- message. And in client side, I get timeout error.
I am trying to figure out where it occurs and why using try-catch and console.log but I can't find any.
This is 'routes/email.js'
var express = require('express');
var router = express.Router();
var db = require('../db');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'ssssss#gmail.com',
pass: 'SSSSSS'
}
});
router.get('/send', function(req, res, next) {
console.log('/send');
var email = decodeURI(req.query.to);
console.log(email);
var rand = Math.floor((Math.random() * 9000 + 1000));
var link="http://"+req.get("host")+"/email/verify?email="+email+"&num="+rand;
var mailOptions={
to : email,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
try{
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.json({result:false,message:"Incorrect email", code:404});
}else{
console.log("Message sent:\n"+JSON.stringify(response, null, 2));
try{
console.log(JSON.stringify(db, null, 2));
var sql = "INSERT INTO email_verification(email, code) VALUES(?,?)";
var input = [email, rand];
db.get().query(sql, input, function(err, result){
if(err) res.json({result:false, message:"SQL error", code:403});
res.json({result:true, message:"Please check your email.", code:100});
});
// res.json({result:false, message:"DB ERROR", code:401});
}catch(e){
console.log(e);
}
}
});
}catch(e){
console.log(e);
}
});
module.exports = router;
db.get().query() part doesn't execute at all.
This is db.js.
const mariadb = require('mariadb');
var pool;
exports.connect = function(done){
console.log("Trying to connect DB...");
pool = mariadb.createPool({
host: 'localhost',
user: 'root',
password: 'ssss',
database:"SSSS",
connectionLimit: 100
});
}
exports.get = function(){
console.log("exports.get");
return pool;
}
The console.log("exports.get"); parts works fine.
This is app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var db = require('./db');
//var passport = require('./passport');
//var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
db.connect(function(err){
console.log(err);
if(err){
console.log('Unable to connect to MariaDB.');
process.exit(1);
}
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', require("./routes/index"));
app.use('/email', require("./routes/email"));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(404);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I just used this db.jsand app.js file from my other project and it worked fine there. But I don't know why this time I have this problem.
Which part and why I am having this problem and how can I fix it?
It'd be easier to work with node.js if I can track the error easily. Figuring out the problematic part takes lots of time. Is there any module or tool for that?

In node.js, the console displays the success log, but localhost: 3000 is not connected

I am creating a simple web application using node.js, express and mysql.
When I connect to get /employees, I try to console.log the data of the linked DB. However, when connected to localhost, an infinite delay occurs.
What's wrong with me?
index.js
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json)
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'ps',
database: 'EmployeeDB'
});
mysqlConnection.connect((err) => {
if(!err)
console.log('DB connection succeded');
else
console.log('DB connection failed \n Error : '+ JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is running at port no:3000'));
app.get('/employees',(res, req)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
console.log(rows);
// console.log(rows[0].EmpID);
else
console.log(err);
})
});
You need to return something, like the data:
app.get('/employees',(req, res)=> {
mysqlConnection.query('SELECT * FROM Employee',(err, rows, fields)=>{
if(!err)
res.json(rows);
else
res.status(500).send('Error found');
})
});
Also, parameters are reversed from normal – (res, req) vs. (req, res) as #JonathanLonowski catch it.

Node.js Express.js MongoDB: route.post() requires callback functions but got a [object Undefined]

I am trying to set up a MEAN (mongodb, express, nodejs, angular6(CLI)) app. Trying to post user signup form data to mongo database, but its throwing an error. It is my first MEAN app, trying to learn.
Do I miss something here?
Error: Route.post() requires callback functions but got a [object Undefined]
server.js
Here is server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var app = express();
var api = require('./server/routes/api');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static(path.join(__dirname + '/dist/meanshopcart')));
app.use('/api', api);
app.post('/sign-up', api.signup);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/meanshopcart/index.html'));
});
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
//app.listen(port, function(){
// console.log("Server is running..!!");
//});
server.listen(port, function(err){
if(err){
return console.log('something bad happened', err);
}
console.log("Server is running..!!");
});
Routes Folder(routes/api.js)
my routes folder ./server/routes/api.js
var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/users');
const db = 'mongodb://localhost:27017/meanshopapp';
mongoose.connect(db, function(err){
console.log("mongo connection done");
if(err){
console.log("Error.."+err);
}
});
router.get('/', (req, res)=>{
console.log("get api ");
User.find({}, function(err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
res.send(users);
});
exports.signup = function(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = router;
Model
this is my user schema user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name : { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
phoneNo: { type: Number },
address: { type: String }
});
module.exports = mongoose.model('user', userSchema, 'users');
You are using exports and module.exports.
Either you should follow #dimagolovin's answer
OR
module.exports = {router};
and use
`app.use('/api', api.router);
app.post('/sign-up', api.signup);`
Try to change the follwing in ./server/routes/api.js
function signup(req, res, next){
console.log("new user entered");
var newUser = new User();
newUser.name = req.body.name;
newUser.email = req.body.email;
newUser.password = req.body.password;
newUser.phoneNo = req.body.phone;
newUser.address = req.body.address;
newUser.save(function(err){
if(err){
console.log("error saving user");
}
else{
console.log("user inserted");
}
})
};
module.exports = {router, signup};
It should do the work

Post Form data to MySQL using Node.js

I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I have posted the code and error below. I'm struggling to resolve this issue.
Error
http://localhost:3000/submit
Error: No default engine was specified and no extension was provided.
at new View (C:\website\node_modules\express\lib\view.js:61:11)
at Function.render (C:\website\node_modules\express\lib\application.js:570:12)
at ServerResponse.render (C:\website\node_modules\express\lib\response.js:1008:7)
at C:\website\index.js:21:9
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at next (C:\website\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\website\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\website\node_modules\express\lib\router\layer.js:95:5)
at C:\website\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\website\node_modules\express\lib\router\index.js:335:12)
index.html
<form action="/submit" method="post">
<input id="name" type="text" name="name" placeholder="Type your name...">
<input id="message" type="text" name="message" placeholder="Type message...">
<input class="submit_message" type="submit" value="Send">
</form>
index.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
connection.connect();
app.get('/submit',function(req,res) {
res.render('index');
});
app.post('/submit',urlencodedParser, function(req, res, next) {
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function(err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
con.query(sql, function(err, result) {
if(err) throw err;
console.log("table created");
});
});
res.render('index', {title: 'Express'});
});
connection.end();
app.listen(3000, function () {
console.log('Listening on port 3000');
});
MySQL database
This is how my database should look like
I have refactored your code, As per question specified. for ex- You need to mention all our static content inside public directory (i.e your index.html), Also you have done syntax error ie- you have written con.query(sql, function(err, result) instead of connection.query(sql, function (err, result), instead of rendering index.html file as you did res.render('index', {title: 'Express'}); its better you send the file to your public/index.html res.sendFile('public/index.html', { root: __dirname }); as specified by #Pogrindis
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mywebsite"
});
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.html');
});
app.post('/submit', urlencodedParser, function (req, res) {
console.log("Im here");
console.log(req.body.name);
console.log(req.body.message);
connection.connect(function (err) {
if (err) throw err;
console.log("connected");
var sql = "INSERT INTO `users` (`name`,`message`) VALUES ('" + req.body.name + "', '" + req.body.message + "')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("table created");
});
});
res.sendFile('public/index.html', { root: __dirname });
});
app.listen(3000, function () {
console.log('Listening on port 3000');
});
please follow the file path as :
I am successfully able to persist the data to my DB which has been entered from input text box(name, message) in index.html.
Happy coding !!

Unable to read body in post response [express.js]

I am making a post request using Restlet client tool in chrome. In console.log(res), I can clearly see that there is body present there with totally correct data but still I am always getting an error message saying body is undefined when doing res.body.
Here is the code
var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(parser.urlencoded({extended: true}));
app.use(parser.json());
var db = mongoose.connection;
var port = process.env.PORT || 8000;
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/',function(req,res){
res.json({msg: 'Welcome to Pre-Health API!'});
});
var User = mongoose.Schema({
first_name: String,
last_name: String
},{
collection: 'User',
timestamps: true
});
router.route('/user').post(function(res,req) {
var user = mongoose.model('user',User);
console.log(req);
var new_user = new user({
first_name: req.body.first_name,
last_name: req.body.last_name
});
user.save(function(err) {
if(err) res.send(err);
res.json({message: "User created"});
});
});
app.use('/api',router);
app.listen(port);
console.log('API Listening on port: ' + port);
In the function you have req and res inverted, it should be:
router.route('/user').post(function(req, res) { ...

Categories