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} )
})
});
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}));
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>
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.
I'm building a nodejs/expressjs application and this is my architecture:
+ routes
- candidate.js
- index.js
+ views
- layout.vash
- register.vash
- server.js
in my server.js file, I put this code to manage routes:
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
app.use('/', routes);
app.use('/candidate', candidate);
in candidate.js, all get requests work fine, but there is a problem in post requests, it can't resolve the path: Cannot POST /caregister
server.js
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
var employer = require('./routes/employer');
var app = express();
app.set('view engine', 'vash');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use('/', routes);
app.use('/candidate', candidate);
app.use('/employer', employer);
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('server is listening to ' + app.get('port'));
});
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.render('index');
});
module.exports = router;
routes/candidate.js
var express = require('express');
var router = express.Router();
var Candidate = require("../models/candidate");
router.get('/', function(req, res){
res.render('candidatelogin'); // relative to candidatelogin.vash
});
router.post('/caregister', function(req, res){
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var passwordConf = req.body.passwordConf;
console.log(username + " " + email);
});
module.exports = router;
views/candidatelogin.vash
#html.extend('layout', function(model){
#html.block('body', function(model){
<h1>Jobseeker</h>
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>
})
})
When using app.use and including a prefix like candidate that means that you should use this prefix to access this route later on.
So your form in candidatelogin.vash should post to /candidate/caregister url:
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/candidate/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>
I am trying to get Form data from html page to Node Js server .
My html file is index.html
<body>
<nav>
<ul>
<li>
Add Product
<div class="dialog" style="display:none">
<div class="title">Add Product</div>
<form action="" method="get">
<input id = "name" name="name" type="text" placeholder="Product Name"/>
<input name="code" type="text" placeholder="Product Code"/>
<input name="category" type="text" placeholder=" Category"/>
<input name="brand" type="text" placeholder="Brand"/>
<input type="submit" value="Ok"/>
</form>
</div>
</li>
<li class="radio">
</li>
</ul>
</div>
</nav>
<p></p>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
after submitting the form there is no action perform by the server just get the url with all details
and My server is server.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
methodOverride = require('method-override'),
hostname = process.env.HOSTNAME || 'localhost',
port = parseInt(process.env.PORT, 10) || 4004,
publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
//Show homepage
app.get("/", function (req, res) {
res.redirect("/index.html");
console.log("shubh ");
});
app.get("/index/", function (req, res) {
res.redirect("/index.html");
console.log("shubham ");
});
app.get("/index/:name", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.body.name + '".');
console.log(res.body);
});
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
dumpExceptions: true,
showStack: true
}));
console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);
Your form action is '', therefor the URL created by the form will be
/?name=xxx&code=yyy etc
From your routing, it seems like you're expecting the url to be in the form of /xxx?code=yyy.
Make your form action '/search' and add the following JS.
app.get("/search", function (req, res){
console.log("shubham batra");
var keyword = req.query.code;
console.log(keyword);
//res.send('You sent the name "' + req.query.name + '".');
});
As your making a get request, request.body won't be set.
You can use as multiple as you want like:
var code = req.query.code;
var category = req.query.category;
var brand = req.query.brand;
req.query if its GET request and req.body if its POST.
change the app.get("/index/:name", function (req, res){
to app.get("/index/:name?", function (req, res){
that your route will match /index/ and /index/anyname routes
and change form action to "/" or something like "/action"