I am trying to build my first app independently but I cannot go through that problem. I will be very grateful if someone helps me understand where the problem is. After click submit button I am getting an error Cannot POST /. I suspect that a mistake i trivial and this is annoying for me. In my opinion problem is in my route file.
Here is my html form (wrote in ejs):
<%- include('includes/start.ejs') %>
<%- include('includes/navbar.ejs') %>
<div class="container">
<p>Here you can create your Tournament!</p>
<form class="form" action="/" method="POST">
<label>Discypline:</label><br>
<input type="text" name="discipline" placeholder="E.G. Chess"><br><br>
<label for="lname">Tournament type:</label><br>
<select name="type">
<option value="Bracket Tournament">Bracket Tournament</option>
<option value="League Tournament">League Tournament</option>
</select><br><br>
<label>Description of Tournament:</label><br>
<textarea name="description" rows="4" cols="50"></textarea><br><br>
<input type="submit" value="Submit"><br>
</form>
<%- include('includes/end.ejs') %>
</div>
Here is my route file:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({extended: false}));
router.use(bodyParser.json());
const Tournament = require('../models/tournament.js')
router.get('/creator', (req, res, next) => {
res.render('../views/creator.ejs');
});
router.post('/creator', (req, res, next) => {
//const tournament = new Tournament()
console.log(req.body.discipline);
return;
});
module.exports = router;
And here is my app code:
const express = require('express');
const app = express();
const path = require('path');
const homeRouter = require('.//routes/home.js');
const creatorRouter = require('.//routes/creator.js');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', homeRouter);
app.use('/', creatorRouter);
app.listen(3000);
Thanks for a help.
Best regards.
Related
I was Trying to make a shopping cart. i was making admin panel in which i need to submit the image for adding product. After creating the Form
<section>
<div class="container mt-4">
<div class="row">
<div class="col-md-6">
<h2 class="text-cnter">Add Product</h2>
<form action="/admin/add-product" method="POST" enctype="multipart/form-data">
<label for="">Name</label>
<input type="text" name="Name" class="form-control">
<label for="">Category</label>
<input type="text" name="Category" class="form-control">
<label for="">Price</label>
<input type="text" name="Price" class="form-control">
<label for="">Description</label>
<input type="text" name="Description" class="form-control">
<label for="">Image</label>
<input type="file" class="form-control">
<button class="btn btn-success mt-4" type="submit">Submit </button>
</form>
</div>
</div>
</div>
</div>
</section>
In admin.js file ( where router of admin )
router.get('/add-products',function(req,res){
res.render('admin/add-products')
});
// router.post('/add-product',function (req,res) {
// console.log('Got it')
// });
router.post( "/add-product", function( req, res ) {
console.log(req.body)
console.log(req.file.Image)
});
module.exports = router;
app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var hbs = require('express-handlebars');
var fileupload =require('express-fileupload');
var bodyParser = require('body-parser');
var userRouter = require('./routes/user');
var adminRouter = require('./routes/admin');
const {allowInsecurePrototypeAccess} = require('#handlebars/allow-prototype-access')
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
//Layout Directory Set
app.engine('hbs',hbs.engine({ extname:'hbs' , defaultLayout:'layout',layoutsDir:__dirname+'/views/layout/',partialsDir:__dirname+'/views/partials'}));
app.engine('handlebars', hbs.engine({
handlebars: allowInsecurePrototypeAccess(hbs)
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(fileupload());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', userRouter);
app.use('/admin', adminRouter);
// 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;
after running with nodemon giving submit button shows
Cannot read property 'Image' of undefined
TypeError: Cannot read property 'Image' of undefined
Btw i was just started on nodejs .Thats why i dont know more about it.
You might want to check this line in your admin.js file:
console.log(req.file.Image)
Based on the error message req.fileis undefined and therefor it can't read Image.
The reason is, that express needs extra middleware to correctly handle multipart/form-data. Check out Multer. This should help you getting all the parts of your form including the file(s).
Also be aware that your file input does not have a same. So you definitely can't find it with Image.
Seems like req.file is undefined, so it can't read the property Image of undefined.
try changing this. first provide a name to your input file
<label for="">Image</label>
<input type="file" name = "img" class="form-control">
try getting the file then using
router.post( "/add-product", function( req, res ) {
console.log(req.body)
console.log(req.files.img)
});
enter image description hereI never faced this problem before but now "req.body.task" is not working and I don't know why its happening.
Here's the form
<form action="/" method="POST">
<div class="input-box">
<input type="text" name="task" id="" class="input-add">
<button type="submit" name="button" class="btn-add">+</button>
</div>
</form>
Here's the post request
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.set(bodyParser.urlencoded({extended: false}));
app.use(express.static("public"));
let items = [];
app.get("/", (req,res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req,res) => {
const item = req.body.task;
console.log(item);
});
app.listen(3000, () => {
console.log("Server running at port 3000");
});
This
app.set(bodyParser.urlencoded({extended: false}));
should be
app.use(bodyParser.urlencoded({extended: false}));
BodyParser is a middleware and should be used using app.use methods.
See the docs for more details
app.set is used to set values to app variables, for example view engines
edit:guys I'm genually new to all of this. here's the html form I used. should i update this question with something else?
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
I'm currently trying to design a simple browser app utilizing express. console.log(req.body) comes back {} and i cant find the solution, been here for the best part of the day lol
Here's my app
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
console.log(req.body);
res.render('index', {
infoVoos: 'acesso_inicial'
});
});
app.post('/pesquisar', function(req,res){
console.log("");
console.log("");
console.log(req.body);
res.send('ok');
});
app.listen(3000);
console.log('############');
console.log('Server on');
console.log('');
module.exports = app;
I changed the parameter of the input tag from "id" to "name" and it's working fine now.
original
<form action="/pesquisar" method="post">
<input type="text" id="cO">
<input type="text" id="cD">
<input type="submit">
</form>
new
<form action="/pesquisar" method="post">
<input type="text" name="cO">
<input type="text" name="cD">
<input type="submit">
</form>
thankx guys
First, Sorry if I got the title wrong, I am new and dunno how to start and the terms,
what I want to do is
<form action="/" method="POST">
<select name="cash" id="first">
<option value="AED">AED</option>...
get the value of 'cash' i.e AED
app.post("/", function(.............) {
request(..............)
var cash = req.body.cash;
console.log(cash);
var data = JSON.parse(body);
var price = data.rates.cash;
console.log(price);
res.send( price);}
make a post request and make api call select the price(AED) and res.send and "How to retrieve POST query parameters?" this didn't help me.
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
const request = require('request');
app.use(express.json());
app.use(bodyParser.urlencoded({
extended: true
}));
You can do something like this.
<form method="post" action="http://127.0.0.1:8080/">
<select name="cash" id="first">
<option value="AED">AED</option>
<input type="submit" value="Submit">
</form>
Enter full URL like
<form action="http://127.0.0.1:8080/" method="post">
Node js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
// access your body data here
app.post('/', function(req, res) {
res.send('You sent the code "' + req.body.cash + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
As I understand correctly you want to:
POST form data to backend
during data processing, request 3rd party API for a price
return a price to the user
The form view index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/" method="POST">
<select name="cash" id="first">
<option value="AED">AED</option>
<option value="USD">USD</option>
</select>
<button id="submit" type="submit">Submit</button>
</form>
<% if (cash && price) { %>
<p>The price for <%= cash %> is <%= price %>.</p>
<% } %>
</body>
</html>
I'm using EJS to conditionally display the price below the <form>.
Here is Express backend:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// I advise you to use axios instead of request for convenience
const axios = require('axios');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
if (req.query.cash && req.query.price) {
res.render('index', { cash: req.query.cash, price: req.query.price });
}
res.render('index', { cash: null, price: null });
});
app.post('/', async function (req, res) {
const cash = req.body.cash;
try {
const response = await axios.post(
'paste_your_url', { cash }
);
res.redirect(`/?cash=${cash}&price=${response.data.price}`);
} catch (err) {
console.log(err);
}
});
app.listen(3000);
When the user enters the page /, Express renders index.ejs view without price information.
When the user submits the form to backend, Express:
reads the data,
requests 3rd party API,
reads the price from 3rd party response,
redirects user back to / with values in query string ?cash=<value>&price=<value>. This let Express render index.ejs with price information.
Also, I used axios instead of request, because it makes code more readable and easier (due to async/await).
I have the following App.js:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser')
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended : true }));
// app.use(bodyParser.urlencoded());
// app.use(bodyParser.json());
app.post('/insert_movie', function (req, res) {
var movieName = req.body.movie_name;
console.log(movieName);
});
// No route matching:
app.use(function (req, res) {
res.sendStatus(404);
});
var server = app.listen(3000, function () {
var port = server.address().port;
console.log('Express server listening on port %s.', port);
});
My html page:
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" id="movie_name">
<input type="text" id="movie_year">
<input type="text" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
When I enter values into the text boxes and press submit, my post method is hit ('/insert_movie'). However movieName is undefined not only that but req.body is {}
Can someone explain to me what I'm doing wrong here as I've gone through many solutions on this website however they're all pointing the body parser being incorrectly setup, I've tried the following:
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
Neither of these fix my issue.
You need to add name attribute to the input elements. That's one of the things your body-parser library needs to parse the form.
<h1> Add new movies</h1>
<form action="/insert_movie" method="POST">
<input type="text" name="movie-name" id="movie_name">
<input type="text" name="movie-year" id="movie_year">
<input type="text" name="movie-url" id="movie_imdb">
<input type="submit" value="Submit" />
</form>
try to use this
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
limit: '500mb',
extended: true,
parameterLimit: 50000
}));
app.use(expressValidator());
app.use(bodyParser.json());
use multer middle ware for req.body
var app = require('express')();
var multer = require('multer);
var upload = multer().any();
//multer().any() upload both array and file
//add the multer middle ware in your router
app.post('/insert_movie',upload, function (req, res) {
var movieName = req.body.movie_name;
console.log(req.body);
console.log(movieName);
});
you can see the official npm blog
https://www.npmjs.com/package/multer