i want to show success flash message in express js ?
But i am getting following error
"Error: express-session is required. npm i express-session",(i installed express-session but still showing error )Where i am wrong ?
Here is my code
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require('body-parser');
var Router = require('router');
var api = express.Router();
var mysql = require('mysql');
var session = require('express-session');
const flash = require('express-flash-notification');
app.post('/addcontact', function(req, res){
var name =req.body.name;
var message =req.body.email;
var phone =req.body.phone;
var sql= "insert into contactus(name,message) values ('"+name+"', '"+message+"')";
con.query(sql,function(err,rows){
if(err) throw err;
})
req.flash('success', 'This is a flash message using the express-flash module.');
res.render('pages/contact');
});
Related
Here my server code
var express = require("express");
var isAuthen = require('./middleware/authorize')
var router = express.Router();
var app = express();
var order_process = require('./routes/order-process');
app.use('/order',isAuthen, order_process);
and here order_process code
var express = require('express');
var bodyParser = require('body-parser');
const bcrypt = require("bcrypt");
var router = express.Router();
var db = require('../models/database');
router.get('/', urlencodedParser, function (req, res) {
try {
console.log(req.params);
}catch(err){
console.log(err);
}
module.exports = router;
http://localhost:3000/order/2
as i know that url should return number 2 ??
i dont know why it cannot return ?
should return correct params from url
Here's an example of how to get the params from a route:
const express = require('express');
const router = express.Router();
const app = express();
app.use('/order', router);
router.get('/:page', (req, res) => {
res.send(`You are viewing page ${req.params.page}`);
});
const server = app.listen(8000);
Then go to http://localhost:8000/order/2 and you should see it say:
You are viewing page 2
I have the following test code
var express = require('express');
const res = require('express/lib/response');
var bodyParser = require('body-parser');
var multer = require('multer');
var campos = multer();
var conf = require('../config/config');
var router = express.Router();
router.post('/', campos.single('foto_1'), async(req, res, next) => {
res.send("teste")
});
module.exports = router;
Now my postman test.
I was getting the error when performing the request using Angular, I isolated the error down to postman and turned out that the error was not related to Angular.
I am learning Node.js I barely touched middlewares... the issue is that I had app.use(express.json). Maybe this was comflicting with multer. Now I can get one file campos.single("") and several campos.array("files").
Developing a mongoose database and I would like some support with the issue I have encountered. I followed the tutorial step by step carefully and I cannot see where I am going wrong
I have installed the “var bodyParser=require(‘body-parser’) module within app.js. I would like to save the data that is inputted within the form in the register view. So within the users.js, I have declared the routers for the register view and router. post. the code is below
When I go to test out the name field form in the register view. I do not see the input passed through the terminal. I receive this error below
404
NotFoundError: Not Found
at C:\Users\Sue\myCommunityFinal2Mongoose\app.js:78:8
at Layer.handle [as handle_request]
(C:\Users\Sue\myCommunityFinal2Mongoose\node_modules\express
\lib\router\layer.js:95:5)
Users.js
router.get('/register', function(req, res, next) {
res.send('register');
});
router.post('/register', function(req, res, next) {
console.log(req.body.name);
});
app.js
var createError = require('http-errors');
var express = require('express');
var hbs = require('hbs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require('express-handlebars');
var bodyParser = require('body-parser')
var session = require('express-session');
var passport = require('passport');
var expressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
app.use(expressValidator({
errorFormatter: function (pram, msg, value) {
var namespace = pram.split('.')
, root = namespace.shift()
, formParam = root;
while (namespace.length) {
fornmParam += '[' + namespace.shift()
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
I went to the app.js file and noticed that I missed out the message validation so I included the code below
app.use(require('connect-flash') ());
app.use(function (req,res,next) {
res.locals.message= require('express-message')(req,res);
next();
});
When I run the code I get the error express-message module missing. So I npm install “ express-message “ but get the error “ code e404, the express module is not found".
Not to sure what to do next, my expected result is to be able to input data into the fields without no error so I can model this data in a MongoDB database.
It seems that express is not installed correctly on your machine.
run `npm cache clean` and try again
If that does not work run npm install #types/express
I don´t know why this code inserts NULL.
When the post request is sent I receive (from res.json(req.body) in index.js) an empty "{}"
I´m using NodeJs, Express 4 and MongoDB.
The name attributes in the post are the same than in the jade
template. I have two forms in the same .jade but with differents names, obviously.
This is not all code, I just put the most important and what is related to the question
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
index.js
var express = require('express');
var bodyParser = require('body-parser');
router.post('/adduser', function(req, res) {
var db = req.db;
var userName = req.body.username;
var userEmail = req.body.useremail;
var userPassword = req.body.userpassword;
var collection = db.get('usercollection');
collection.insert({
username : userName,
email : userEmail,
password : userPassword
}, function (err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
}
else {
res.json(req.body);
}
});
});
module.exports = router;
Have you tried putting
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
At the top of your index.js and removing var db = req.db from the route.
Also, you can return the newly created document from the call back in your response.
Your index.js file would now look like this.
index.js
var express = require('express');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/registredUsers');
router.post('/adduser', function(req, res) {
var userName = req.body.username;
var userEmail = req.body.useremail;
var userPassword = req.body.userpassword;
var collection = db.get('usercollection');
collection.insert({
username : userName,
email : userEmail,
password : userPassword
}, function (err, doc) {
if (err) {
res.send("There was a problem adding the information to the database.");
}
else {
res.json(req.body); // <- here you could return the new object instead.
// res.json(doc);
}
});
});
module.exports = router;
edit
To assist the OP I made the following suggestion:
Hardcode var userName = 'test' and return the created document in res.json(doc) in order to test that the database is updating.
I am new to Node.JS I am trying to compile a node with express API but without success, Tried to debug the App just stops in the first module import, I create similar app from tutorial ran well but not saving input data, code bellow:
URL: localhost:3000/api/v1/students
Server.js
// Dependences
var bodyParser = require("body-parser");
var express = require("express");
var mongoose = require("mongoose");
var app = express();
//connect to database
mongoose.connect("mongodb://localhost/rest_test");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get("/api/v1",require("./routes/api"));
app.listen(3000,
function(req,resp)
{
console.log("is Working bitch!");
});
./routes/api.js
var express = require("express");
var router = express.Router();
var Students = require("../models/Students");
Students.methods(["get","post","put","delete"]);
Students.register(router, "/Students");
module.exports = router;
./models/Students.js
var restful = require("node-restful");
var mongoose= restful.mongoose;
var StudentSchema = new mongoose.Schema(
{
name : String,
course : String
});
module.exports = restful.model("Students",StudentSchema);
Solved,
Instead of get must be use:
app.use("/api/v1",require("./routes/api"));