I'm doing a full stack web dev course. I follow along the instructor, but he was able to put bullet points upon HTML form input but I can't. There are some unnecessary code from previous lectures. But here is my code:
list.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
</head>
<body>
<h1>
<%= kindOfDay %>
</h1>
<ul>
<li>Buy Ganja</li>
<li>Roll Ganja</li>
<li>Smoke Ganja</li>
<% for(var i=0;i<newListItems.lenth; i++){ %>
<li> <%= newListItems[i] %></li>
<% } %>
</ul>
<form action="/" method="post">
<input type="text" name="newItem">
<button type="submit" name="button">Add</button>
</form>
</body>
</html>
And here is my server file:
App.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
var items = [];
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
var today = new Date();
var options = {
weekday: "long",
day: "numeric",
month: "long",
};
var day = today.toLocaleDateString("en-US", options);
res.render("list", { kindOfDay: day, newListItems: items });
});
app.post("/", function (req, res) {
var item = req.body.newitem;
items.push(item);
res.redirect("/");
});
app.listen(3000, function () {
console.log("Server Started at Port 3000");
});
Here is the screenshot. I cannot add extra points upon form submission!
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(express.urlencoded({extended:true}));
app.get("/",function(req,res){
var today = new Date();
var options = {
weekday: "long",
year:"numeric",
day: "numeric",
month:"long"
};
var day = today.toLocaleDateString("en-US",options);
res.render("index",{kindOfDay:day,tasks:tasks});
})
var tasks = [];
app.post("/",function(req,res){
const task = req.body.newItem;
tasks.push(task);
res.redirect("/");
})
app.listen(3000,function(){
console.log("Server is running");
})
<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
</head>
<body>
<h1><%= kindOfDay %> </h1>
<ul>
<li>Buy Food</li>
<li>Watch Movies</li>
<% for(var i=0;i<tasks.length;i++){ %>
<li><%= tasks[i] %> </li>
<% } %>
</ul>
<form action="/" method="POST">
<label for="newItem">Add New Task</label>
<input type="text" name="newItem" id="newItem">
<button type="submit">Add</button>
</form>
</body>
</html>
Related
I am trying to create a simple form handler using express. I tried the code below for my form:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="./css/style.css" rel="stylesheet" type="text/css">
<script src="./js/register.js"></script>
<title>CAMPEONATO</title>
</head>
<body>
<div class="main-login">
<div class="left-login">
<h1>Cadastre-se<br>E participe do nosso campeonato</h1>
<img src="./img/soccer-animate.svg" class="left-login-image" alt="Futebol animado">
</div>
<form action="http://localhost:3000/register" method="POST">
<div class="right-login">
<div class="card-login">
<h1>Crie sua conta</h1>
<div class="textfield">
<label for="name">Nome Completo</label>
<input type="text" name="txtName" id="name" onchange="validateFields()" placeholder="Nome Completo">
</div>
<div class="textfield">
<label for="email">E-mail</label>
<input type="email" name="txtEmail" id="email" onchange="validateFields()" placeholder="E-mail">
</div>
<div class="textfield">
<label for="password">Senha</label>
<input type="password" name="txtPassword" id="password" onchange="validateFields()" placeholder="Senha">
</div>
<button class="btn-login" type="submit" id="login-button" disabled="true">CRIAR</button>
</div>
</div>
</form>
</div>
</body>
</html>
Here is my index.js:
// config inicial
const express = require('express')
const mongoose = require('mongoose')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
// forma de ler JSON / middlewares
app.use(
bodyParser.urlencoded({
extended: false,
}),
)
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));
// rotas da API
const usersRoutes = require('./routes/usersRoutes')
app.use('/users', usersRoutes)
app.use('/register', usersRoutes)
And here is my routes/usersRoutes:
const router = require('express').Router()
const Users = require('../models/Users')
// CREATE - Criacao de Dados
router.post('/register', async (req, res) => {
// req.body
const{ name } = req.body.txtName;
const{ email } = req.body.txtEmail;
const{ password } = req.body.txtPassword;
const users = {
name,
email,
password
}
try {
await Users.create(users)
} catch (error) {
res.status(500).json({error:error})
}
})
module.exports = router
I keep getting the error "CANNOT POST /" after submitting the form. I've tried everything on the internet but the error remains, am I forgetting some module? Forgetting a route?
I am trying to make this simple app where I would fetch some data from a free public API that would show the population of a specific state. However, I am having difficulty updating the population variable and I cannot figure out the problem. the app logs the population properly but fails to update it in the app it self.
/* Requiring NPM packages */
const express = require("express");
const ejs = require("ejs");
const fetch = require("node-fetch");
const bodyParser = require("body-parser");
const _ = require("lodash");
/* Using Express */
const app = express();
const port = 3000;
/* Using Static Files */
app.use(express.static(__dirname + "/public"));
/* Using ejs*/
app.set("view engine", "ejs");
/* Using Body-Parser */
app.use(bodyParser.urlencoded({ extended: true }));
/* Fetching API data */
let nation = "Not Chosen";
let year = "Not Chosen";
let myStatePopulation = "TBD";
const data = async (nation, year) => {
const response = await fetch(
"https://datausa.io/api/data?drilldowns=State&measures=Population&year=" +
year
);
const myJson = await response.json();
const allState = myJson.data;
let myState = allState.find((x) => x.State === nation);
myStatePopulation = myState.Population;
console.log(myStatePopulation);
};
// data();
/* Starting the server */
app.get("/", function (req, res) {
res.render("index", {
content: "United States Population",
state: nation,
year: year,
population: myStatePopulation,
});
});
/* Posting Data */
app.post("/", function (req, res) {
if (req.body.stateName && req.body.yearDate) {
nation = _.capitalize(req.body.stateName);
year = Number(req.body.yearDate);
data(nation, year);
res.redirect("/");
} else {
nation = "Not Chosen";
year = "Not Chosen";
myStatePopulation = "TBD";
console.log("redirecting to main page");
res.redirect("/");
}
});
app.listen(port, () => console.log("app is running on port : " + port));
just to make it more clear here is the content of the ejs file
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/css/styles.css" />
<title>US Population</title>
</head>
<body>
<div class="header centertext">
<h1><%= content %></h1>
</div>
<div class="content centertext">
<p>State : <%= state %></p>
<p>Year : <%= year %></p>
<p>Population : <%= population %></p>
</div>
<div class="form centertext">
<form action="/" method="post">
<div class="form inputs">
<input type="text" name="stateName" placeholder="type your state" />
</div>
<div class="form inputs">
<input
type="text"
name="yearDate"
placeholder="type your desired year (2013-2020)"
/>
</div>
<div class="form submit">
<button type="submit">Sumbit</button>
</div>
</form>
</div>
</body>
</html>
My index.js file on root directory
const express = require("express");
const app = express();
const path = require("path");
const axios = require("axios").default;
const cors = require("cors");
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));
app.use(
cors({
origin: "http://localhost:3000",
})
);
fetchData = async () => {
const data = await axios.get(
"https://nepse-data-api.herokuapp.com/data/todaysprice"
);
console.log(data);
return data;
};
app.get("/", (req, res) => {
const nepseData = fetchData();
res.render("home.ejs", { nepseData });
});
app.listen(3000, () => {
console.log("listening to port 3000");
});
My home.ejs file on views directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<%= nepseData %>
</body>
</html>
The browser is displaying this when I run the server
The API is sending this type of data
I want to show the name and prices on my ejs file. What should I do now??
You have to add await there:
app.get("/", async (req, res) => {
const nepseData = await fetchData();
res.render("home.ejs", { nepseData });
});
And then you can iterate over the data:
<% nepseData.forEach(function(row){ %>
<%= row.companyName %> <%= row.minPrice %>
<% }); %>
here is my app.js
const express = require('express');
const upload = require("express-fileupload");
const app = express();
app.use(upload());
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res){
if(req.files){
console.log(req.files);
}else{
console.log("error");
}
})
app.listen(3000, function(){
console.log("Success");
})
and here's the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>File upload in node js</h1>
<form action="/" method="POST">
<input type="file" name="file">
<button type="submit" value="upload">upload</button>
</form>
</body>
</html>
i get "error" from the console which means req.files is empty or does not exist i guess
i don't know how to fix this, i've started using fileupload today so i'm not that familiar to that
Help please
when submitting a file, you must use the multipart / formdata tag. see
<form action="/" method="POST" enctype='multipart/form-data'>
<input type="file" name="file">
<button type="submit" value="upload">upload</button>
</form>
also, when making a post request with javascript, you must send it as new FormData (). see
I am trying to follow this example, but I don't see the message "Hello World from client" on the brower. For that matter, I don't see the Client connected....
I do see the Hello World and the form .
app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
client.emit('messages', 'Hello from server');
});
});
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
index.html
<!doctype html>
<html lang="en">
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
<head>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
<script> tag just could resides in <head> or <body> tags. If you are going to manipulating the dom and not using a DomReady function to check whether the dom is ready or not, then you should place all your script tags at the end of your body tag just before </body>:
<!doctype html>
<html lang="en">
<head>
<title>My App</title>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
</body>
</html>