code
I am not sure why the below does not work .I tried to add app.use(express.json()); in index.js but still not working. Any idea on how to solve this?
when I console.log it shows undefined
I am trying to console log the data that is submitted in the html
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
const { path } = require('express/lib/application');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile(__dirname + "/Signup.html")
})
app.post('/Signup.html', function (req, res) {
var fname = req.body.fname
var lname = req.body.lastname
var email = req.body.email
console.log(fname, lname, email)
})
app.listen(3000, function () {
console.log("Running in 3000 ")
})
HTML
this is the html code
<form action="/Signup.html" method="post" >
<img class="mb-4" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcST1ViA_OmDA31rfd8ooDSmjLUeuh-HujXTwA&usqp=CAU" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating top">
<input type="text" name="fname" id="fname" class="form-control top" placeholder="First Name" required>
<label for="floatingInput">First Name</label>
</div>
<div class="form-floating middle">
<input type="text" class="form-control middle" name="lastname" placeholder="Last Name">
<label for="floatingPassword">Last Name</label>
</div>
<div class="form-floating bottom">
<input type="email" class="form-control bottom" name="email" placeholder="email">
<label for="floatingPassword">Email</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign Me Up</button>
<p class="mt-5 mb-3 text-muted">© The App Brewery</p>
</form>
Related
This is my register page and here ı m handling multipart form ...
import React, { useEffect, useState } from "react";
import { Next } from "react-bootstrap/esm/PageItem";
import { Link } from "react-router-dom";
import CheckedCompany from "./includes/CheckedCompany";
import axios from "axios";
export default function Sigin() {
const [companyType, setCompanyType] = useState(false);
const clickHandlerCompanyType = (event) => {
setCompanyType(!companyType);
console.log("Im here");
};
const [checked, setchecked] = useState(false);
const checkedPerson = (event) => {
setchecked(!checked);
};
const [name, setName] = useState("");
const [surname, setSurname] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [image, setImage] = useState("");
const submitHandler = (e) => {
axios({
url: "http://localhost:5000/user/register",
method: "POST",
data: {
name,
surname,
email,
password,
userType: checked ? "2" : "1",
image,
},
headers: {
"Content-Type": "multipart/form-data",
},
withCredentials: true,
crossDomain: true,
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
return (
<div class="container pt-5 mb-2">
<div class="row">
<div class=" container col-md-12 ">
<div class=" container card my-1">
<h5 class="card-title text-center">Yeni Kayıt</h5>
<div class="card-body">
<div className="row ">
<div className="col-6 ps-5">
<div class="mb-3 form-check">
{" "}
<label class="form-check-label" for="exampleCheck2">
Bireysel
</label>
<input
checked={!checked}
onChange={checkedPerson}
type="radio"
class="form-check-input"
name="flexRadioDefault"
/>
</div>
</div>
<div className="col-6 ps-5">
<div class="mb-3 form-check">
<input
onChange={checkedPerson}
type="radio"
class="form-check-input"
name="flexRadioDefault"
></input>
<label class="form-check-label" for="exampleCheck2">
İşletme
</label>
</div>
</div>
</div>
<form onSubmit={submitHandler}>
<div class="mb-3">
<label for="formFile" class="form-label">
Resim
</label>
<input
class="form-control"
type="file"
name="image"
onChange={(e) => {
setImage(e.target.files[0]);
console.log(e.target.files[0]);
}}
/>
</div>
<div class="mb-3">
<label for="name" class="form-label">
Adınız
</label>
<input
type="text"
class="form-control"
name="name"
onChange={(e) => setName(e.target.value)}
></input>
</div>
<div class="mb-3">
<label for="surname" class="form-label">
Soyadınız
</label>
<input
type="text"
class="form-control"
name="surname"
onChange={(e) => setSurname(e.target.value)}
></input>
</div>
<div class="mb-3">
<label for="email" class="form-label">
E-posta adresiniz
</label>
<input
type="email"
class="form-control"
name="email"
onChange={(e) => setEmail(e.target.value)}
></input>
</div>
<div className="mb-3">
{" "}
<label for="password" class="form-label">
Şifre
</label>
<input
type="password"
class="form-control"
name="password"
aria-describedby="passwordHelp"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{checked
? CheckedCompany({
companyType,
clickHandlerCompanyType,
setCompanyType,
})
: null}
<div class="mb-3">
<div id="passwordHelp" class="form-text">
şifremi unuttum
</div>
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
id="exampleCheck1"
></input>
<label class="form-check-label" for="exampleCheck1">
Bireysel Üyelik Sözleşmesini ve Ekleri'ni{" "}
Kabul ediyorum
</label>
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
id="exampleCheck2"
></input>
<label class="form-check-label" for="exampleCheck2">
İletişim bilgilerime kampanya, tanıtım ve reklam içerikli
ticari elektronik ileti gönderilmesine, bu amaçla kişisel
verilerimin işlenmesine ve tedarikçilerinizle paylaşılmasına
izin veriyorum
</label>
</div>
<p class="card-text text-center">
<button type="submit" class="btn btn-primary">
Üye Ol
</button>
</p>
</form>
</div>
</div>
<div class="card">
<div class="card-body">
Bu sayfadaki bilgiler 4teker.com üyeliği için alınmaktadır.
Kişisel verilerin korunması hakkında detaylı bilgiye{" "}
buradan ulaşabilirsiniz.
</div>
</div>
</div>
</div>
</div>
);
}
I'm sending the form with axios to api
const express = require("express");
const app = express();
const cors = require("cors");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const mongoDbStore = require("connect-mongodb-session")(session);
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
require("dotenv").config();
const port = process.env.PORT;
//Routes
const postRoutes = require("./routes/post.route");
const userRoutes = require("./routes/user.route");
//Middlewares
const store = new mongoDbStore({
uri: process.env.ATLAS_URI,
collection: "Sessions",
});
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./public/img/");
},
filename: function (req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
app.use(express.static("public"));
app.use(multer({ storage }).single("image"));
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
},
store,
})
);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
app.use(express.json());
//DB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Db is connected");
});
app.use("/user", userRoutes);
app.use("/post", postRoutes);
app.listen(port, () => {
console.log("Port 5000 is listening...");
});
I mean there shouldnt be any problem ,but there it is :d
Can you guys help me ?
Btw error is on below.
Error: Multipart: Boundary not found
at new Multipart (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\types\multipart.js:58:11)
at Multipart (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\types\multipart.js:26:12)
at Busboy.parseHeaders (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\main.js:71:22)
at new Busboy (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\busboy\lib\main.js:22:10)
at multerMiddleware (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\multer\lib\make-middleware.js:33:16)
at Layer.handle [as handle_request] (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:275:10)
at serveStatic (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\serve-static\index.js:75:16)
at Layer.handle [as handle_request] (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\musa2\OneDrive\Masaüstü\calisma-Workinon\backend\node_modules\express\lib\router\index.js:275:10)
const express = require("express");
const handlebars = require("express-handlebars");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine(".hbs", handlebars({ defaultLayout: "main", extname: ".hbs" }));
app.set("view engine", ".hbs");
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
mongoose.Promise = global.Promise;
mongoose.connect(
"mongodb://usresa:passcode#mongodb-rukshi-shard-00-00.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-01.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-02.nerbj.gcp.mongodb.net:27017/db_name?ssl=true&replicaSet=atlas-dxrzem-shard-0&authSource=admin&retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true }
);
const nameSchema = new mongoose.Schema({
name: String,
naquantityme: String,
description: String,
});
const User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.render("login", { layout: "loginlayout" });
});
app.get("/home", (req, res) => {
res.render("dashboard", { layout: "main" });
});
app.use("/AddProduct", (req, res) => {
res.render("AddProduct", { layout: "main" });
});
app.post("/addproductform", (req, res) => {
var myData = new User(req.body);
myData
.save()
.then((item) => {
res.send("Product saved to database");
})
.catch((err) => {`enter code here`
res.status(400).send("Unable to save to database");
});`enter code here
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
///// Front End
<form id="form_validation" method="post" action="/addproductform">
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Product Name" name="name"
required>
</div>
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Quantity" name="quantity"
required>
</div>
{{!-- <div class="form-group">
<div class="radio inlineblock m-r-20">
<input type="radio" name="gender" id="male" class="with-gap" value="option1">
<label for="male">Male</label>
</div>
<div class="radio inlineblock">
<input type="radio" name="gender" id="Female" class="with-gap" value="option2"
checked="">
<label for="Female">Female</label>
</div>
</div> --}}
<div class="form-group form-float">
<textarea name="description" cols="30" rows="5" placeholder="Description"
class="form-control no-resize" required></textarea>
</div>
{{!-- <div class="form-group">
<div class="checkbox">
<input id="checkbox" type="checkbox">
<label for="checkbox">I have read and accept the terms</label>
</div>
</div> --}}
<button class="btn btn-raised btn-primary waves-effect" id="submitDetails"
name="submitDetails" type="submit">SUBMIT</button>
</form>
This is appjs code. Rest I have AddProduct in views folder.
The default setting for accesing the view is from views folder.
This addproduct form is not submitting the datat to database.
How do we change the route of different views
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.
I have created a form for signing up a user. I want to fetch the values from the form using body-parser but I am not able to do so. While prinnting in the console it gives undefined printed. I don't get what am I doing wrong. I even tried using postman but it doesn't work. Here is my code:
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
passport = require('passport'),
LocalStrategy = require('passport-local'),
methodOverride = require('method-override'),
flash = require('flash'),
session = require('express-session');
app.get("/about", function(req, res) {
res.render("about");
});
app.get("/register", function(req, res) {
res.render("register");
});
app.post("/register", function(req, res) {
var firstName = req.body.firstName,
lastName = req.body.lastName,
username = req.body.username,
email = req.body.email;
var newUser = new User({
firstName: firstName,
lastName: lastName,
username: username,
email: email
});
console.log(firstName + " " + req.body.password + " " + req.body.c_password);
User.register(newUser, req.body.password, function(err, user) {
if(err) {
return res.render("register", {'error': err.message});
}
passport.authenticate('local')(req, res, function() {
req.flash('success', 'Welcome ' + user.username);
res.redirect('/home');
})
})
});
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("Service Running");
});
And here is my form
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hotel Site</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css" integrity="sha384-REHJTs1r2ErKBuJB0fCK99gCYsVjwxHrSU0N7I1zl9vZbggVJXRMsv/sLlOAGb4M" crossorigin="anonymous">
<link rel="icon" href="https://www.svgrepo.com/show/12002/hotel.svg" type="image/x-icon">
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container" style="margin-bottom: 4.5rem;">
<h1 style="text-align: center; margin-top: 7rem; margin-bottom: 20px">Sign Up</h1>
<div class="col-lg-6" style="margin: auto;">
<form action="/register" method="POST" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-6">
<input class="form-control" type="text" name="firstName" placeholder="First Name" required>
</div>
<div class="form-group col-6">
<input class="form-control" type="text" name="lastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<input class="form-control" type="text" name="username" placeholder="Username" required>
</div>
<!-- <div class="form-group">
<input class="form-control" type="email" name="email" placeholder="E-mail" required>
</div> -->
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password" required>
</div>
<div class="form-group">
<input class="form-control" type="password" name="c_password" placeholder="Confirm Password" required>
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">Submit</button>
</div>
</form>
Go Back
</div>
</div>
</body>
Help very much appreciated!!!
Express uses middleware, which are functions that have access to incoming requests. Requests can be modified etc. Simply put middleware can be used for lots of things.
You have not setup bodyParser as middleware so it will not work. This can be done by:
app.use(bodyParser.urlencoded({extended: false})) for form data
app.use(bodyParser.json()) for incoming JSON before your routes.
Here's the ExpressJs guide on middle: https://expressjs.com/en/guide/writing-middleware.html
You've successfully imported body-parser into your app, but you've failed to use it. Add the following code before you use your routes.
app.use(bodyParser.urlencoded({ extended: false }))
I hope it was helpful.
I have the file upload api, which send out the SUCCESS message on the file upload and the FAILURE message when the file not selected.
app.js
const express = require("express");
const app = express();
const http = require("http").Server(app).listen(3000);
const upload = require("express-fileupload");
const request = require("request");
app.use(express.urlencoded());
app.use(express.json());
app.use(upload({
useTempFiles: true,
tempFileDir: '/tmp/'
}));
console.log("Server Started");
// To load both HTML and CSS files on the root call
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
}
)
app.post("/", function (req, res) {
if (req.files.filename.name) {
res.send("uploaded");
}
else
res.send("Please select the file to upload!");
})
Instead res.send(), i want to display some modal box defined on my html code. Need a help on how to incorporate or shown this modal box upon my post request.
index.html
<link rel="stylesheet" href="index.css">
<div class="hdngTab">
<h1 style="align-content: center"> Utility</h1>
</div>
<div class="test">
<form label="upload" method="post" enctype="multipart/form-data" action="/">
<div class="sf-ref">
<label> Ticket Reference </label>
<input type="text" name="sftext"> </input>
</div>
<br><br>
<input style="font-size: 20px; padding-left: 180px" type="file" name="filename">
<!--input style="font-size: 20px" type="submit" value="Upload"-->
<button class="trigger" style="font-size: 20px" value="Upload">
Upload </button>
</form>
</div>
<div class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h1>Hello, I am a modal!</h1>
</div>
</div>
I have a simple CRUD app in Node.js/Express. It's an order intake form to post data to a MongoDB collection.
I cannot for the life of me see why this POST (CREATE) route is not succeeding. I’ve been troubleshooting this all morning. My other routes run just fine as validated with my console.logs.
Here is my orders route file (/routes/orders.js):
var express = require("express");
var router = express.Router();
var Order = require("../models/order.js");
// Load Keys ===================================================================
const keys = require('../config/keys');
// INDEX ROUTE - show all orders
router.get("/", isLoggedIn, function(req, res){
// Get all orders from DB
Order.find({}, function(err, allOrders){
if(err){
console.log(err);
} else {
res.render("orders", {orders:allOrders});
//Test to see if this returns the number of records in the collection
console.log("There are currently " + allOrders.length + " orders.");
}
});
});
// CREATE ROUTE - add new order to the DB
router.post("/", isLoggedIn, function(req, res){
// get data from form and add to newOrder object
var date = req.body.date;
var territory = req.body.territory;
var principal = req.body.principal;
var customer = req.body.customer;
var representative = req.body.representative;
var amount = req.body.amount;
var newOrder = {date: date, territory: territory, principal: principal, customer: customer, representative: representative, amount: amount};
// Create a new order and save to DB
Order.create(newOrder, function (err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to orders page
res.redirect("/");
console.log("New order created (orders route file).");
}
});
});
// NEW ROUTE - show form to create new customer
router.get("/new", isLoggedIn, function(req, res){
res.render("new.ejs");
console.log("This is coming from the order route js file.");
});
This is my new.ejs template file with the form:
<div class="container container-new py-5">
<div class = "row">
<div class="col-lg-12 orders-title">
<h2>New Order</h2>
</div>
</div>
<div class="row">
<div class="col-md-10 mx-auto">
<form action="/orders" method="POST">
<div class="form-group row">
<div class="col-sm-3">
<label for="inputDate">Date</label>
<input type="text" class="form-control" id='datetimepicker' name="date">
</div>
<div class="col-sm-3">
<label for="inputTerritory">Territory</label>
<select id="selectTerr" class="form-control" name="territory">
<option>Choose a territory</option>
</select>
</div>
<div class="col-sm-6">
<label for="inputPrincipal">Principal</label>
<select id="selectPrin" class="form-control" name="principal">
<option>Choose a principal</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-5">
<label for="inputCustomer">Customer</label>
<select id="selectCust" class="form-control" name="customer">
<option>Choose a customer</option>
</select>
</div>
<div class="col-sm-4">
<label for="inputRepresentative">Sales Rep</label>
<select id="selectRep" class="form-control" name="representative">
<option>Choose a rep</option>
</select>
</div>
<div class="col-sm-3">
<label for="inputState">Total</label>
<input type="text" class="form-control" id="inputTotal" name="amount">
</div>
</div>
<div class="form-group new-buttons">
<button type="button" class="btn btn-cancel btn-default btn-primary px-4">Clear</button>
<button type="button" class="btn btn-submit btn-default btn-primary px-4">Submit</button>
</div>
</form>
</div>
</div>
<div class = "row row-back">
<div class="col-lg-12 orders-title">
Back to Main
</div>
</div>
</div>
app.js:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
methodOverride = require("method-override"),
seedDB = require("./seeds");
// seedDB();
// Requiring Routes ============================================================
var ordersRoutes = require("./routes/orders"),
indexRoutes = require("./routes/index");
// Load Keys ===================================================================
const keys = require('./config/keys');
// Map global promises
mongoose.Promise = global.Promise;
// Mongoose Connect ============================================================
mongoose.connect(keys.mongoURI, {
useMongoClient: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//==============================================================================
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use("/orders", ordersRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server started on port ${port}`));