404 Error while saving data to mongoDb from node.js & express - javascript

im currently trying to save some data from Bootstrap input fields into my mongoDB database but i always get the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). I tried to change the Routes but i cant find my mistake. My Schema is in a file called movie.js.
I Feel like i dont really get the Route thing of express, im very new at this.
<div class="container">
<div class="row">
<div class="col">
<form method="post" action="/insertMovie">
<h1 class="text-center pt-5">Neuen Film anlegen</h1>
<div class="form-group">
<label>Titel</label>
<input
type="text"
class="form-control"
placeholder="Titel eingeben"
name="title"
/>
</div>
<div class="form-group">
<label>Beschreibung</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="description"
/>
</div>
<div class="form-group">
<label>Startdatum</label>
<input
type="text"
class="form-control"
placeholder="Startdatum eingeben"
name="start"
/>
</div>
<div class="form-group">
<label>Aktuell laufend</label>
<input
type="text"
class="form-control"
placeholder="Beschreibung eingeben"
name="currentlyRunning"
/>
</div>
<input id="submit" type="submit" class="btn btn-primary" />
</form>
</div>
</div>
</div>
movies.js
const express = require("express");
const router = express.Router();
const Movie = require("../models/movie");
router.get("/", async (req, res) => {
try {
const movies = await Movie.find();
res.json(movies);
} catch (err) {
res.json({ message: err });
}
});
router.post("/insertMovie", async (req, res) => {
const movie = new Movie({
title: req.body.title,
description: req.body.description,
start: req.body.start
});
try {
const savedMovie = await movie.save();
res.json(savedMovie);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
app.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
//Middlewares
app.use(bodyParser.json());
app.use(cors());
//Import Routes
const moviesRoute = require("./routes/movies");
app.use("/movies", moviesRoute);
// include a static file serving middleware
app.use(express.static(__dirname + "/"));
// Get all Data
app.get("/data", function(req, res) {
res.sendfile("index.html");
});
// Insert new Movie
app.get("/insertMovie", function(req, res) {
res.sendfile(__dirname + "/insert.html");
});
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true });
app.listen(3000);

The issue here is with your movie routes. With the way you set it up, your endpoint is actually:
localhost:3000/movies/insertMovie
but you are using:
localhost:3000/insertMovie

Related

set attribute 'src' to an element in html using nodejs

I use 'express' nodejs and using this code to send url into text
<form method="GET" action='/download' class="my-5">
<div class="form-group">
<label for="exampleInputEmail1"
>Link:</label
>
<input
type="text"
class="form-control"
placeholder="Enter URL"
name="url"
/>
</div>
<button type="submit" class="btn btn-primary">Download</button>
</form>
in my project I receive
const express = require("express");
const app = express();
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
return res.render("index");
});
app.get("/download", async(req, res) => {
console.log(req.query.url);
});
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
as you can see I use get '/download' to receive url from input and doing some analazing to output new url
my quation is : how can I set this new url to an arttibute 'src' for element (such as img) in homepage without loading new page?
I need only put this new url to be value in 'src' for img in index.eje
app.get("/", (req, res) => {
return res.render("index",
{
srcAttr: 'link to image'
}
);
});
<img src="<%= srcAttr %>">

Can't create new document on POST (mongoose/express)

Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
HTML IS TOTALLY CORRECT WRITTEN I THINK PLEASE TELL ME WHATS WRONG IN THIS APP.JS CODE
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyparser = require('body-parser')
const path = require('path');
mongoose.connect('mongodb://localhost:27017/ContactPage');
const port = 3000;
var contactSchema= new mongoose.Schema({
name:{type:String},
email:{type:String},
project:{type:String},
message:{type:String}
});
var Contact = mongoose.model('Contact', contactSchema);
module.exports = Contact;
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({extended: true}))
app.set('view engine', 'ejs');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/',(req,res)=>{
var myData = new Contact(req.body);
myData.save().then(()=>{
res.send(req.body)
}).catch(()=>{
res.status(400).send(req.body);
});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Check My Node.js code Please I want to Save Contact page data in mongoose compass this don't throw any error but also not saving data
<form action="/" class="contact_form grid" method="POST">
<div class="contact_inputs grid">
<div class="contact_content">
<label for="" class="contact_label">Name</label>
<input type="text" name= "name" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Email</label>
<input type="email"name="email" class="contact_input">
</div>
</div>
<div class="contact_content">
<label for="" class="contact_label">Project</label>
<input type="text" name="project" class="contact_input">
</div>
<div class="contact_content">
<label for="" class="contact_label">Message</label>
<textarea name="" id="" cols="0" rows="7" name = "message" class="contact_input"></textarea>
</div>
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
</form>
#1 you are not submitting from HTML, so instead of:
<div>
<a href="" class="button button--flex">
Send Message
<i class="fas fa-paper-plane button_icon"></i>
</a>
</div>
write:
<button type="submit">
Send Message
</button>
#2 express improvements
contactSchema file:
const mongoose = require('mongoose')
var contactSchema = new mongoose.Schema({
name: { type: String },
email: { type: String },
project: { type: String },
message: { type: String }
});
module.exports = mongoose.model('Contact', contactSchema);
app file:
const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser')
const path = require('path');
const port = 3000;
const app = express();
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded({ extended: true }))
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, "index.html"))
});
app.post('/', (req, res) => {
var { name, email, project, message } = req.body;
var myData = new Contact({
name,
email,
project,
message,
});
myData.save().then((newData) => {
res.send(newData)
}).catch((err) => {
res.status(400).send("Error: ", err, " , Data: ", req.body);
});
});
app.listen(port, () => {
mongoose.connect('mongodb://localhost:27017/ContactPage')
.then(() => console.log("Server & DB listening at http://localhost:${port}"))
.catch(err => console.log(err));
})

Cannot read property 'username' of undefined...something to do with body-parser

I need to log the username from the file register.ejs to my console
i have checked the code soo many times and i couldn't get the solution the is error.. plz help me out
this is my /register file:
<!-- Makes POST request to /register route -->
<form action="/register" method="POST">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-dark">Register</button>
</form>
</div>
</div>
</div>
This is my app.js file:
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.set("view engine", "ejs");
app.use(express.static("publica"));
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/userDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
email: String,
password: String,
});
const User = mongoose.model("User", userSchema);
app.get("/", (req, res) => {
res.render("home");
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/register", (req, res) => {
res.render("register");
});
app.post("/register", function (req, res) {
console.log(req.body.username);
});
app.listen(3000, () => {
console.log("All Good Bruh!!!");
});
im trying to log the username from /register page but im getting this error:
Cannot read property 'username' of undefined
Please help me out
add app.use(bodyParser.urlencoded({ extended: true }));
some where up

invalid csrf token express

I'm learning about backend and I have a problem with csurf protection in my express nodejs project. When I submit in add-admin form is working find, but add-product form and edit-product form I receive the error
invalid csrf token
403
ForbiddenError: invalid csrf token
this is my app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const Product = require('./models/product');
var app = express();
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
require('./config/passport')(passport);
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout', extname:'.hbs', runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret:'mysupersecret',
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 30*60*24*60*1000}
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/static',express.static('public'));
app.use(function(req,res,next){
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
//routes
app.use('/admin', adminRouter);
app.use('/user', userRouter);
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(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;
My admin.js
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var multer = require('multer');
var mongoose = require('mongoose');
var async = require('async');
var {check, validationResult} = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var csrfProtection = csrf();
router.use(csrfProtection);
mongoose.connect('mongodb://localhost:27017/project3', {useNewUrlParser: true, useUnifiedTopology: true});
var Product = require('../models/product');
var User = require("../models/user");
// add-product page
router.get("/add-product",csrfProtection,
function(req,res,next) {
var messages = req.flash('error');
res.render('admin/add-product', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0,
});
});
//edit-product page
router.get("/edit-product/:id", csrfProtection,function(req,res,next){
Product.findById(req.params.id, function(err, data){
if(err) {
throw err;
} else {
res.render("admin/edit-product", {
csrfToken: req.csrfToken(),
editedProduct:data,
});
}
});
});
//delete a product
router.get("/delete-product/:id", function(req,res,next){
Product.deleteOne({_id: req.params.id}, function(err){
if(err) {
throw err;
} else {
res.redirect("../list-product");
}
});
});
//list admin
router.get('/list-admin', function(req,res,next){
User.find({rule: 2}, function(err,admin){
if(err) {
throw err;
}
else {
res.render('admin/list-admin', {
csrfToken: req.csrfToken(),
admin: admin
});
}
});
});
// add account admin
router.get('/add-admin', function(req,res, next) {
var messages = req.flash('error');
res.render('admin/add-admin', {
csrfToken: req.csrfToken(),
messages: messages,
hasErrors: messages.length>0
});
});
module.exports = router;
my add-user.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="/admin/add-product" method="post" id='checkout-form' enctype="multipart/form-data">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
</div>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thêm sản phẩm</button>
</form>
</div>
</div>
edit-product.hbs
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offet-3">
<form action="../edit" method="post" id='edit-form' enctype="multipart/form-data" >
<div class="row">
<input type="hidden" name="IDChar" value={{editedProduct._id}}>>
<div class="col-xs-12">
<div class="form-group">
<label for="name">Tên sản phẩm</label>
<input type="text" id="name" value="{{editedProduct.name}}" class="form-control" required>
</div>
</div>
<hr>
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit" class="btn btn-success">Thay đổi</button>
</form>
</div>
</div>
add-admin.hbs
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h3>Thêm tài khoản admin</h3>
{{#if hasErrors}}
<div class="alert alert-danger">
{{#each messages}}
<p>{{this}}</p>
{{/each}}
</div>
{{/if}}
<form action="/admin/add-admin" method='post'>
<div class="form-group">
<label for="email">Email</label>
<input type="text" id ="email" name = "email" class="form-control">
</div>
<div class="form-group">
<label for="password">Mật khẩu</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button type="submit"class="btn btn-primary">Thêm tài khoản Admin</button>
</form>
</div>
</div>
i searched in google and document of csurf but i can't find resolve. Please help me, thank you for watching.

Node.js Express SQLite3: Can't Send HTML input data to SQLite3

Basically, I'm trying to add an ArtistId and Name using an HTML input into my SQLite3 database. Every time I press the submit button, I receive a '404 - Not Found' page instead of the '/success' page that I set up in my view folder, and my database is not being updated. I have run a simple test to make sure that I'm connected to the database which is successful - it is commented out in the code. For this, I am using Express, Handlebars, and SQLite3. Please help me understand how to do this properly. Thanks in advance.
<form action="/form" method="POST">
<div>
<label for="ArtistId">Artist Id: </label>
<input type="text" name="artistId">
</div>
<div>
<label for="name">Name: </label>
<input type="text" name="name">
</div>
<div>
<button type="submit" value="submit">Submit</button>
</div>
</form>
Express
const express = require('express');
const router = express.Router();
const app = express();
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const db = new
sqlite3.Database('./Chinook_Sqlite_AutoIncrementPKs(2).sqlite');
// const query = `SELECT * FROM Artist LIMIT 5`;
// db.each(query, (err, row) => {
// if (err) throw err;
// console.log(row);
// });
//
// db.close();
router.get('/form', function(req, res, next) {
res.render('form');
});
app.post('/form', (req, res, next) => {
db.run(
`INSERT INTO Artist(ArtistId, Name) VALUES(${req.body.artistId},
${req.body.name})`,
(err, row) => {
if (err) throw err;
res.redirect(303, '/success');
}
);
});
module.exports = router;

Categories

Resources