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;
Related
i am currently trying node & express. The Project is a small Movie Library. Today i tryed to implement a search for titles of movies, the problem i have is when i submit my form and get my query String like this http://localhost:3000/movies/?title=Hustlers i get all the Data in my Database. But when i manually type the Url like this http://localhost:3000/movies/title=Hustlers it works fine and i get the matching result. I tryed change my Routes but i am stuck right now.
here is the movies.js
const express = require("express");
const router = express.Router();
const Movie = require("../models/movie");
//Get Back all the movies
router.get("/", async (req, res) => {
try {
const movies = await Movie.find();
res.json(movies);
} catch (err) {
res.json({ message: err });
}
});
//specific Movie
router.get("/title=:title", async (req, res) => {
try {
const movie = await Movie.find({ title: req.params.title });
res.json(movie);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
my 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());
app.use(express.urlencoded());
const moviesRoute = require("./routes/movies");
app.use("/movies", moviesRoute);
app.use(express.static(__dirname + "/"));
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true });
app.listen(3000);
and my submit form here
<form action="/movies/">
<input type="text" name="title" />
<input
type="submit"
value="Suchen"
class="btn btn-primary btnNewMovie"
/>
</form>
The = is messing it up, because that character is reserved for the query component. It would also look much cleaner as /title/movie_title. Try this:
router.get("/title/:title", async (req, res) => {
try {
const movie = await Movie.find({ title: req.params.title });
res.json(movie);
} catch (err) {
res.json({ message: err });
}
});
There's a difference between query string params and route params.
When you submit a form, normally it will encode the request as application/x-www-form-urlencoded (More info here), then the express router parse those values and provide them thru the query hash. For more information on how to properly use the route params on express go here and read the Route parameters section.
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
I'm learing ExpressJS, i want to do the login part , but i gave me this
Cannot POST /login
im using the post method why it gave me this error
here a detailed post , thank you in advance for helping me
html part
<form method="POST">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" >
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password">
<button type="submit">Login</button>
</div>
</form>
The route.js
router.post('/login'),(req,res)=>{
var username= req.body.name;
var password = req.body.password;
con.query('SELECT * FROM authentication WHERE username = ?',username, function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if(results[0].password == password){
res.send({
"code":200,
"success":"login sucessfull"
});
}
else{
res.send({
"code":204,
"success":"username and password does not match"
});
}
}
else{
res.send({
"code":204,
"success":"username does not exits"
});
}
}
});
}
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
when trying to post this form i'm getting:
Cannot POST /login
what am i missing here?
You should handle current page, not '/login' page in route.js :
router.post('/', //...
Instead of writing
router.post('/login', //...
Because you sent the form data to the current page not to the '/login' page
Why current page ?
Because, you didn't define action attribute in your form
You need to define form action
<form action="/login" method="post">
But I recommend you to use js for sending requests
fetch('/login', {
method: 'POST',
body: JSON.stringify(yourFormData),
// ...another Opts if it needs
})
Also it can be problem with your server code because I don't see defining router in indexRouter file, you should add it:
const express = require('express');
const router = express.Router();
// then your code:
router.post('/login', loginController);
But you can add this line for check post requests:
app.post('/login', (req, res) => {
res.status(201).json(req.body); // or console.log
});
I´ve just started learning NodeJS to use as a back-end of my applications, but this is my first time working with a server-side technology.
I am trying to build a simple app which is a form where I want to insert the data into the database (mongodb) and get the data to display on the front end. I am using express-handlebars.
The data is successfully being saved into the database, however when I am trying to get the data from the database to display on the front end nothing happens.
Does anyone knows what may be wrong with my code ?
Thank you!!
//code begins here
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var assert = require('assert');
var url = 'mongodb://felipe:teste#ds033125.mlab.com:33125/form';
mongoose.connect(url);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
// INSERT DATA INTO DATABASE(MONGODB)
router.post('/insert', function(req, res, next) {
var Schema = mongoose.Schema;
var itemSchema = new Schema({
nome: String,
sobrenome: String,
nacionalidade: String,
email: String
});
var CreateItem = mongoose.model('CreateItem', itemSchema);
var item = new CreateItem({
nome: req.body.getNome,
sobrenome: req.body.getSobrenome,
nacionalidade: req.body.getNacionalidade,
email: req.body.getEmail
});
item.save(function(err) {
if (err) throw err;
console.log(item.nome + ' was saved!');
});
res.redirect('/');
console.log(item.nome + ' ' + item.sobrenome + ' was saved!');
});
// GET DATA FROM MONGODB AND DISPLAY ON THE FRONT END
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongoose.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('createitems').find();
cursor.forEach(function(err, doc) {
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close;
res.render('index', {items: resultArray});
});
});
res.redirect('/');
});
// HTML where the data will be displayed
{{# each items}}
<tr>
<div class="col-md-3">
<td class="data">{{ this.nome }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.sobrenome }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.nacionalidade }}</td>
</div>
<div class="col-md-3">
<td class="data">{{ this.email }}</td>
</div>
</tr>
{{/each}}
do not use this: {{ this.nome }}
just use it like that: {{ nome }}
Take reference from this example, i have created one route which you can access at (http://localhost:3000/test) you need to start the express server before accessing this route, This route will get the data from mongo db using mongoose and will return it. You can try this route using postman.
var express = require("express"),
app = express(),
bodyparser = require("body-parser"),
mongoose = require("mongoose");
const router = express.Router();
app.use(bodyparser.json());
mongoose.connect('mongodb://localhost:27017/test');
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB connected successfully');
})
var schema = new mongoose.Schema({
name: String,
value: String
})
var data=mongoose.model("testdata", schema);
router.route('/test').get((req, res) => {
data.find((err, (testdata);=> {
if (err)
console.log("Found some error" + err)
else
res.json(testdata);
})
})
app.use('/', router);
app.listen(3000, function () {
console.log('server started on port 3000');
});
I want to save the information captured from an html form in a MongoDB database, I have the following code:
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
</html>
And the following javascript code would be my app.js
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
/*
mongoose.Promise = global.Promise;mongoose.connect("mongodb://localhost:27017/node-demo");
*/
var promise = mongoose.connect('mongodb://localhost:27017/node-demo', {
useMongoClient: true,
/* other options */
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
Apparently the post request is working, filling in the fields and pressing the input type submit, however when checking the database is empty, just as it was when it was created. Does anyone know why I do not save the information?
I run your code here and the app.post was not called. It's because you're using app.use to send the index.html. app.use is used to bind middleware to your application. Instead, you should use app.get, which tells express to listen for requests to / and run the function when it sees one.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});