req.body returns empty on post - javascript

I'm pretty new to Express. not sure what I did wrong...
Here's a quick mockup of my situation.
app.js
const app = express();
const bodyParser = require('body-parser')
const port = 3000;
app.set('view engine', 'pug');
app.use('/static', express.static('./public'));
const urlEncoded = bodyParser.urlencoded({ extended: false });
const jsonParser = bodyParser.json();
app.get('/', (req, res) => {
res.render('index')
});
app.get('/form', (req, res) => {
res.render('form');
});
app.post('/', urlEncoded, (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`This app is listening on localhost:${port}`);
});
form.pug
block content
form(action="/" method="post")
label(for="name")
input(for="name" id="name")
input(type="submit")
the result in the console is an empty object.

You are confusing between id and name tag.The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted and this is what you are missing in your html form . So, just add a name attribute.
block content
form(action="/" method="post")
label(for="name")
input(for="name" id="name" name = "name")
input(type="submit")

Related

How to get access to variable from post into get method with mongoDB

i created variable in app.post, and i want to use it in app.get, but before this i added this one to my database, but i don't know how to get access to this variable in other function, here is my code
const express = require("express");
const { default: mongoose } = require("mongoose");
const app = express();
const port = 3000;
const Task = require(`./models/task`);
require("./db/moongose");
// sendFile will go here
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.get("/task", (req, res) => {
res.render("../public/mainPage.ejs", {tasks: mongoose});
});
app.post("/task", async (req, res) => {
const task = new Task({
description: req.body.task,
});
try {
await task.save();
console.log(task.description);
res.redirect("/task");
} catch (e) {}
});
app.listen(port);
console.log("Server started at http://localhost:" + port);
and all i want to do is get acces to task.description in app.get

With res.render("url", {object}) the url doesn't change but the view is changed

I'm building a e-commerce page using express and when i want to delete one of my products everything seems to work fine but the url doesn't change (and it should).
So here is my code:
//route
router.use('/product', require('./product.routes'))
router.delete('/item/:id', productController.deleteProduct);
//controller
deleteProduct: (req, res) => {
let id = req.params.id;
let newDatabase = database.filter((item) => item.id != id);
fs.writeFileSync(path.join(__dirname, '../database/productos.json'), JSON.stringify(newDatabase, null, 4), {encoding: 'utf-8'});
let productVisited = newDatabase.filter(item=>item.category=="visited");
let productInSale = newDatabase.filter(item=>item.category=="in-sale");
res.render("home", {newDatabase, productVisited, productInSale });
}
}
//EJS
<form method="POST" action="/product/item/<%= database.id %>?_method=DELETE">
<input type="submit" class="action-button delete" value="ELIMINAR">
</form>
//ENTRY POINT (APP.JS)
const express = require('express');
const path = require('path');
const methodOverride = require ('method-override');
const app = express();
app.use(express.static(path.join(__dirname, "./public")));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
app.set("views",path.join(__dirname, "./src/views"));
app.use("/", require ("./src/routes/index.routes"));
app.use((req, res, next) => {
res.status(404).render('error')
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server Running')
})
Thanks in advance for your time! have a nice day

ExpressJS redirect index.html

JS,
I have an express app with some routes. When my router doesn't match any route it will display index.html instead of going to route '/*' and redirect to a specific route.
I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1.
Maybe I can do something with express-static but I don't know how.
And if I name my file home.html instead of index.html it's work perfectly.
Here is a small piece of my code :
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');
const port = 3080;
let csrfProtection = csrf({ cookie: true })
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
res.status(403).json({error: "Invalid CSRF Token"});
})
app.post('/roles', csrfProtection, (req, res) => {
/*...*/
});
app.get('/test', csrfProtection, (req, res) => {
/*...*/
});
app.all('/*', csrfProtection, (req,res) => {
if(Object.keys(req.query).length == 0) {
res.redirect("https://my-domain.com/test?id=1");
}
res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
My files structure is :
home
static
css
js
index.html
index.js
At the request for https://my-domain.com, write res.redirect('/foo/bar'), where /foo/bar is the url you want to redirect to.
See Official Documentation For res.redirect(): http://expressjs.com/en/api.html#res.redirect

node js express app.get and app.post does not work

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too
is it replaced with something in the newer versions of express or something?
here is my code:
const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
//next line does not work
//if I use app.use it will work fine
app.get("/product",(req,res)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req,res)=>{
res.send("<h1>done</h1>")
})
app.listen(3000);
Your code is working fine. For the print body, you should have to use bodyParser in express js.
const express = require('express');
let app = express();
var bodyParser = require('body-parser')
app.use('/addp', (req, res, next) => {
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({ extended: true }));
app.use(
bodyParser.json({
limit: "250mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "250mb",
extended: true,
parameterLimit: 250000
})
);
app.get("/product", (req, res) => {
res.send("Get Request")
})
app.post("/product", (req, res) => {
console.log("-------------")
console.log(req.body);
console.log("-------------")
res.send("Post Request")
})
app.use('/', (req, res) => {
res.send("<h1>done</h1>")
})
app.listen(3000);
It is this:
app.route('/product/').get(function (req, res) {
If u want to add multiple routes let's say api, u will do this:
In some module api.js:
const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});
Then let's say your server:
app.use('/api', apiRoutes);

Express form parsing not working

I've been using Express.js and the body-parser module for parsing a form to the server. However, when the content is received, res.body it just shows up as an empty object.
app.js:
var express = require("express");
var app = express();
var bp = require("body-parser");
app.set('views', __dirname + '/views');
app.use(bp.json());
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index.jade');
});
app.post('/', function (req, res) {
console.log(req.body);
});
app.listen(process.env.PORT || 5000);
The form (in Jade):
form(method="post", action="/", enctype="application/json")
input(type="text", name="name", placeholder="input your name")
Why is this so and how can it be fixed?
bodyparser.json() only parses requests with JSON data. You need to use bodyparser.urlencoded():
app.use(bodyParser.urlencoded({extended: false}))
extended: false means that nested values aren't handled, e.g. foo[bar]=baz. You can switch it to true if you want to support nested values.

Categories

Resources