Express-fileupload req.files empty - node.js

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

Related

Why do I get the error "Cannot POST /" when submitting a form?

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?

Cannot Make a To-Do-List app using Ejs Templating

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>

POST Route to END Route

I am building a Node.JS website and need to change my current GET Route to POST route. How do I successfully make the conversion. My current error is 'Cannot GET /' Then I need to have the POST Route hit the GET route.
const express = require('express');
const path = require('path');
const hbs = require('express-handlebars');
// Moment.js
var moment = require('moment');
// Init App
const app = express();
// Json File
const json = require("./data.json");
// Javascript Files
const welcomeTime = require('./public/javascript/welcomeTime');
// Load View Engine
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout',
layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(__dirname+'/public'));
// GET Route
// app.get('/', function(req, res){
// res.render('index', {
// title: 'NodePark',
// hotel: 'NodePark',
// firstName: json.payload.data.Source_FirstName,
// lastname: json.payload.data.Source_LastName,
// date: moment().format('ll'),
// time: moment().format('LT'),
// currentHour: welcomeTime.dayTime()
// });
// });
// POST Route
app.post('/', function(req, res){
res.render('index', {
title: 'NodePark',
hotel: 'NodePark',
firstName: json.payload.data.Source_FirstName,
lastname: json.payload.data.Source_LastName,
date: moment().format('ll'),
time: moment().format('LT'),
currentHour: welcomeTime.dayTime()
});
});
// Start Server
app.listen(5000, function(){
console.log('Port 5000 open for business.');
});
I have included my working GET Route and an attempt at the POST Route. I do not understand why it is not working.
layout.hbs is below
<!doctype HTML>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>{{ title }}</title>
<link href="https://fonts.googleapis.com/css?family=Fanwood+Text:400i" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lora" rel="stylesheet">
<link rel="stylesheet" href="/stylesheets/style.css">
<style>li span { position: relative; left: -8px; }</style>
</head>
<body>
{{{ body }}}
</body>
</html>
index.hbs is below
<div id="body-container">
<div id="header">
<div id="logo-content">
<div id="logo"></div>
</div>
<div id="welcome">
<p>Good {{ currentHour }} {{ firstName }} {{ lastname }}. We hope your stay is comfortable & relaxing.</p>
</div>
</div>
{{!-- <div id="time-side">
<div id="time-content">
<p> {{ date }} <br> {{ time }} </p>
</div>
</div> --}}
</div>
{{!-- end of header --}}
<div id="background">
<img src="images/villaView.jpg" alt="villaView">
</div>
<div id="footer">
<p> <br> © 2018 NodePark </p>
</div>
My goal is to create an endpoint in which goes from POST route to GET route.
In your post handler, call res.redirect("<new-url>") to redirect the user to <new-url>.
// POST Route
app.post('/', function(req, res){
// store the incoming data somewhere, e.g. in a cookie-based session
res.redirect('/');
});
// GET Route
app.get('/', function(req, res){
// retrieve the posted data from somewhere, e.g. from a cookie-based session
res.render('index', { ... });
});

Express - Cannot POST /quotes

Note I did shuffle through a LOT of answers, couldn't find one that matched mine.
Trying to learn express and node. When submitting the form in index.html, the following returns "Cannot POST /quotes" in browser and nothing in the console, but the GET method works fine and loads the page.
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening to port 3000");
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post('/post', (req, res) => {
console.log("Hellloooooooooo!");
});
index
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<form action="/quotes" method="POST">
<input type="text" placeholder="name" name="name">
<input type="text" placeholder="quote" name="quote">
<button type="submit">SUBMIT</button>
</form>
</body>
</html>
there is no quotes route, you have only 2 routes and only one post /post route but no post /quotes route
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening to port 3000");
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post('/post', (req, res) => {
console.log("Hellloooooooooo!");
});
// just make a simple quotes route
app.post('/quotes', (req, res) => {
console.log("hello from quotes route!");
});

Examples not returning message to client

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>

Resources