req.body returns undefined in this part
res.send("Texto "+req.body.titulo+" Conteudo "+req.body.conteudo)
the result is Texto undefined Conteudo undefined
Why is this happening?
I tried using app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) instead of expres, but bodyParser is deprecated.
index.js:
const express = require('express');
const app = express();
const handlebars = require('express-handlebars');
const bodyParser = require('body-parser');
const Post = require('./models/Post');
// Config
// Template Engine
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
// Body Parser
app.use(express.json({limit:'20mb'}));
app.use(express.urlencoded({extended:false, limit:'20mb'}));
// Rotas
app.get('/cad', function(req, res){
res.render('formularios');
});
app.post('/add', function(req, res){
res.send("Texto "+req.body.titulo+" Conteudo "+req.body.conteudo);
});
app.listen(8081, function(){
console.log("Servidor rodando na URL http://localhost:8081");
});
here is the code that posts to /add. formularios.handlebars:
<form action="/add" method="post">
<div>
<label for="titulo">Título:</label>
<input type="text" name="titulo" id="titulo_id">
</div>
<div>
<label for="conteudo">Conteúdo:</label>
<input type="text" name="conteudo" id="conteudo_id">
</div>
<div class="button">
<button type="submit">Cadastrar postagem</button>
</div>
</form>
Related
I am trying to get the text that is typed in by the user in my html input field and push it into an array. But the body of my request ist always empty. I already tried changing the order of code but it is not helping. Where is the Problem?
app.js file:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const gameRouter = require('./routes/game.js');
const siteRouter = require('./routes/site.js');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/game', gameRouter);
app.use('/', siteRouter);
app.listen(3000);
game.js file in the folder routes:
const express = require('express');
const router = express.Router();
const games = [];
router.get('/game', (req, res, next) => {
});
router.post('/create', (req, res, next) => {
console.log(req.body);
games.push({game: req.body.game})
res.redirect('/');
})
module.exports = router;
ejs file for html generating:
<%- include('./includes/head.ejs') %>
</head>
<body>
<%- include('./includes/nav.ejs') %>
<h1>Create a new Game</h1>
<main>
<form action="/game/create" method="POST">
<div>
<input type="text" id="game">
<button type="submit">start</button>
</div>
</form>
</main>
<%- include('./includes/end.ejs') %>
You need to add name attribute to the input element:
<input type="text" name="game" id="game">
Use this line before app.use():
// For parsing a JSON file
app.use(bodyParser.json())
// For parsing parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
So i am making something for fun and i am new to express.js and ejs i made a minecraft server status checker and i want to display the result in <%=text%> from express.js but i am getting this error
ReferenceError: C:\Users\UwU\OneDrive\Desktop\UwU web\Web Development\Firebones-Site\views\index.ejs:110
108| <input type="submit" value="Submit" />
109| </form>
>> 110| <h1><%= text %></h1>
111| </div>
112| </body>
113| <script src="js/effect.js"></script>
text is not defined
my index.ejs
<form action="/" method="GET">
<input type="text" name="uwu" required />
<input type="submit" value="Submit" />
</form>
<h1><%= text %></h1>
express (main.js)
//Imports
const express = require("express");
const res = require("express/lib/response");
const app = express();
const port = 3000;
const path = require("path");
const util = require('minecraft-server-util')
app.use(express.static("public"));
app.use("/css", express.static(__dirname + "public/css"));
app.use("/js", express.static(__dirname + "public/js"));
app.use("/img", express.static(__dirname + "public/img"));
app.set("views", "./views");
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
var input = req.query.uwu;
util.status(input)
.then((response) => {
var players = response.players.online;
var maxplayers = response.players.max;
res.render("index", {text: players} )
})
});
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
// app.use(express.urlencoded({extended:false}));
// app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json())
router.get('/add-product', (req, res, next) => {
res.send('<form action="/product" method="POST"><input type="text" id="fname" name="fname"><br><input type="submit" value="Submit"></form>')
})
the response isn't parsed .. I tried 1k things .. Nothing works... i still receive undefined
i tried both variants **app.use(bodyParser.urlencoded({extended:true})); and app.use(express.urlencoded({extended:false})); + app.use(bodyParser.json()) and app.use(express.json());**
What's to do ? thank you in advance
you should have app.get and not router.get
See here
I'm building a simple notes app using express and MongoDB and I got this kind of bug where I can't update the description of the Notes, just the Title. This the form from where I'm getting the data:
<div class="col-md-4 mx-auto">
<div class="card">
<div class="card-header">
<h3>Edit Note</h3>
</div>
<div class="card-body">
<form action="/notes/edit-note/{{note._id}}?_method=PUT" method="POST" >
<input type="hidden" name="_method" value="PUT">
<div class="form-group">
<input type="text " class="form-control" placeholder="title" name="title" value="{{note.title}}">
</div>
<div class="form-group">
<textarea name="decription" id="decription" style="width: 100%;" class="mt-4"placeholder="description">{{note.description}}</textarea>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Save</button>
</div>
</form>
</div>
</div>
I think thats working fine cause when I console.log(req.body) I get the following:
{ _method: 'PUT', title: 'some text', decription: 'some text' }
Based on this I think the error might be on the JS
My Index.js is the following:
const express = require("express");
const exphbs = require("express-handlebars");
const path = require("path");
const methodOverride = require("method-override");
const session = require("express-session");
const bodyParser = require('body-parser');
//init
const app = express();
require("./database");
//settings
app.set("port", 3000);
app.set("views", path.join(__dirname, "views"));
app.engine(
".hbs",
exphbs({
defaultLayout: "main",
layoutsDir: path.join(app.get("views"), "layouts"),
partialsDir: path.join(app.get("views"), "partials"),
extname: ".hbs",
})
);
app.set("view engine", ".hbs");
//Middleware
app.set(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended:true}))
app.use(methodOverride("_method"));
app.use(
session({
secret: "mysecretapp",
resave: true,
saveUninitialized: true,
})
);
//Global varaibles
//routes
app.use(require("./routes/index"));
app.use(require("./routes/notes"));
app.use(require("./routes/users"));
//Static files
app.use(express.static(path.join(__dirname, "public")));
//Server listening
app.listen(app.get("port"), () => console.log("App listening on port 3000!"));
My Schema is the following:
const mongoose=require('mongoose')
const {Schema} = mongoose;
const NoteSchema=new Schema({
title:{type: String, required:true},
description:{type: String, required:true},
date:{type: Date,default:Date.now},
})
module.exports= mongoose.model('Note',NoteSchema)
finally this is the code for the oruter from where in tryin to make the update
const express = require("express");
const router = express.Router();
const Note = require("../models/Note");
router.put("/notes/edit-note/:id", async (req, res) => {
console.log(req.body);
const title = req.body.title;
const description = req.body.description;
await Note.findOneAndUpdate(
{ _id: req.params.id },
{ '$set': { title: title, description: description } }
);
res.redirect("/notes/notes");
});
module.exports = router;
Found the error on
<textarea name="decription" id="decription" style="width: 100%;" class="mt-4"placeholder="description">{{note.description}}</textarea>
name should be 'description', that fixed the problem.
[Development Env] nodejs v4.2.4 + expressjs v4.13.1 + csurf v1.8.3
I successfully installed csurf middleware but It seems like not working.
I tried submitting form without csrf input field to test it works and there was nothing err. So I inserted console.log codes into router js file
console.log(res.locals._csrf);
and I recieved 'undefined'.
I inserted input field to verify the value exist, html result also had not csrfToken
<input name="_csrf" value="" type="hidden">
What can I do? This is html source
<form class="form" method="post" action="/login" role="form">
<input type="hidden" name="_csrf" value="{{_csrf}}">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput1">User Name</label>
<input class="form-control" name="userName" id="focusedInput1" type="text">
</div>
<div class="form-group">
<div class="form-group label-floating">
<label class="control-label" for="focusedInput2">password</label>
<input class="form-control" name="user_pw" id="focusedInput2" type="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" style="float:left">Login</button>
<button type="button" class="btn btn-default" style="float:right" data-dismiss="modal">Cancel</button>
</div>
</form>
and This is app.js
// module importing
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
exphbs = require('express-handlebars'),
mongoose = require('mongoose'),
csrf = require('csurf');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var routes = require('./routes/index');
var users = require('./routes/users');
var credentials = require('./credentials.js');
var app = express();
// mongoose Setup
mongoose.connect(credentials.mongooseRsrc.collUrl);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', exphbs({defaultLayout: 'single', extname: '.hbs'}));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(credentials.cookieSecret));
app.use(session({
resave: false,
saveUninitialized: false,
secret: 'sfbsesc',
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(csrf());
app.use(function(req, res, next){
res.locals._csrf = req.csrfToken();
});
//skip
I had the same issue and worked around it by passing the token in through the controller.
In your routes controller, for your POST /login, pass in the token as an object on response.
router.post('/login', (req, res) => {
res.render('login', {
_csrfToken: req.csrfToken(),
});
});
This could cause issues with other routes depending on how they're set up, but if you encounter errors saying token is invalid, you probably just need to pass it into that route as well