I have a simple html uploading form
<h1>Upload File Here</h1>
<form methods="post" enctype="multipart/form-data" action="/">
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
I want uploaded files to hit a "/upload" folder. I am using the following express code to do this.
const express = require("express");
const app = express();
upload = require("express-fileupload");
app.listen(80);
app.use(upload());
console.log("Server Started");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req, res) => {
if (req.files) {
var file = req.files.filename,
filename = file.name;
file.mv("/upload/" + filename, err => {
if (err) {
console.log(err);
res.send("error occured");
} else {
res.send("done!");
}
});
}
});
When I start the server and go to localhost in Chrome, I see the upload form. If I try to upload something, the url box changes to reflect the file I tried to upload, but the file does not appear in the '/upload' folder. Any ideas on what obvious mistake I'm making??
Thanks!
The solution is in my form. I need to set the action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
The solution is in my form. I need to set the
action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
Related
I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})
I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})
I am learning express node.js and trying to run simple calculator code but anytime i press on the button i don't get any response back and also i don't get any errors in my code so i am kind of lost of what i am doin wrong. here is the sample of it so hoping someone can pinpoint me where i am goin wrong will include html code and calculator.js. Thank you in advance.
index.html
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="button" name="submit">Calculate</button>
</form>
</body>
calculator.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
//this line to show result in hyper
console.log(req.body);
res.send("The result is: " + result);
});
app.listen(3000, function(){
console.log("Server running on port 3000");
});
the problem lies in your button type. To submit a form using a button in html, you need to specify the type not as button, but as type.
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="submit" name="submit>Calculate</button>
</form>
I have tried to do file upload in express js project. used ejs as default view engine.
file not uploaded to /uploads folder.
here is my code below.
in app.js file have imported required packages
in routes/index.js route file created route
router.get('/index',indexController.index);
router.post('/insertion',indexController.insertion);
module.exports = router;
in controllers/indexController.js
const multer = require('multer');
const path = require('path');
const storage = multer.diskStorage({
destination:function(req,file,cb)
{
cb(null,'./../uploads');
},
filename:function(req,file,cb)
{
callback(null,file.originalname);
}
});
var upload = multer({storage:storage}).single('resume');
exports.insertion = function(req,res)
{
var file = req.files.resume;
upload(req,res,function(err){
if(err)
{
console.log(err);
}else{
console.log('file uploaded successfully!');
}
});
res.end();
}
in views/registration.ejs file
<form name="registration" action="/insertion" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label>Resume</label>
<input type="file" name="resume" class="form-control" >
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</div>
</form>
file uploading not working .. i need to upload the file under uploads folder which is created in root directory
I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs