I'm trying a simple form submission code, and I'm using post method.
My server.js code
//N-4E;V-56;I-49
//var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var idx = require('./index.js');
var ra = require('./ra.js');
var app = express();
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'html');
app.set('port',process.env.PORT || 5649);
app.use(bodyParser.urlencoded({extended: true}));
app.use('/',idx);
app.use('/reg_path',ra);
app.listen(app.get('port'),function(){
console.log('Express started press asdfadsfasdfasdf');
});
my index.js
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.get('/',function(req,res,next){
//res.sendHeader(.)
res.render('index.ejs',{});
//res.render('title.ejs',{});
});
module.exports = router;
my index.ejs
<!DOCTYPE html>
<html>
<head>
</head>
</body>
<div id="reg_path">
<p>Enter the Regressions Folder Path</p>
<form action="/reg_path" method="post" enctype="multipart/form-data">
<fieldset>
<label for="path">Path:</label>
<input type="text" id="path" name="path" placeholder="Enter the Absolute path"/>
<input type="submit" value="Enter"/>
</fieldset>
</form>
</div>
</body>
</html>
my ra.js is
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express.Router();
var path;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post("/",function(req,res){
console.log(req.body.path);
path = req.body.path;
fs.access('path',fs.constants.F_OK, (err) => {
if (err) throw err;
res.redirect('./index');
//if (err) {
// res.writeHead(404,{'Content-Type':'text/plain'});
// return res.end('The specified path "' + path + '" does not exists');
//}
});
//fs.access('path',fs.constants.R_OK, (err) => {
// //if (err) {
// // res.writeHead(404,{'Content-Type':'text/plain'});
// // return res.end('The specified path "' + path + '" has no READ permissions');
// //}
//});
});
module.exports = app;
Now, from the index page, when I type a path in the form, and press the submit, in the console.log the 'req.body' is returned as 'undefined'.
most of the code in ra.js is commented or not updated because the 'req.body' value is unavailable in the first place. I need to correct it first.
I've searched through internet to try and figure out the mistake that is in my code, but to my vain I'm unable to uncover it. Any help is much appreciated
node version:v6.11.0
body-parser :1.17.2
express :4.15.3
ejs :2.5.6
Your form uses enctype="multipart/form-data" which is an encoding type that body-parser doesn't support.
If you need to use this type (for instance, if you're going to be uploading files from your form), take a look at multer.
Otherwise, leave out the enctype attribute so the form will default to application/x-www-form-urlencoded.
Related
How do I post a value which is on the client-side and get it on the server-side.
example:
<form action="/myform" method="POST">
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.get('/myform', function(req, res){
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
app.listen(3000)
<form action="http://127.0.0.1:3000/myform" method="post">
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myform', function(req, res) {
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
Your code seems to be fine, apart from wrong method name. In HTML form you have mentioned POST method but at server you are listening to GET method. So just change, app.get('/myform', to app.post('/myform',.
It should work.
I want to send a file with express-busboy. On the readme it says that you can use req.body. So i did. The regular inputs worked, but the file inputs just returned the name of the file i uploaded. I uploaded the file called myfile.png and in the textinput, i put the value of 'Hello World'. I want the send the file that i upload to a folder called mydir (which is in ./). Here is a sample of code:
//js:
const express = require('express');
const mysql = require('mysql');
const bp = require('body-parser');
const session = require('express-session');
const uc = require('upper-case');
const busboy = require('express-busboy');
const fs = require('fs');
const util = require('util');
const app = express();
app.use(bp.urlencoded({ extended: true }));
busboy.extend(app, {
upload: true,
path: './mydir'
});
app.post('/somewhere', (req, res) => {
console.log(req.body.textinput);
//returns the 'Hello World'
console.log(req.body.imginput);
//returns 'myfile.png'
});
<html>
<body>
<form action="/somewhere" method="post" enctype="multipart/form-data">
<input type="text" name="textinput">
<input type="file" name="imginput" accept='image/*'>
</form>
</body>
</html>
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.
Please can you help me out, for some reason I am not able to post and am getting a "cannot POST /api/create" and when inspecting the page a 404 error is shown.
Here is my index.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mainRouter = require('./mainRouter.js');
var todoRoutes = require('./todoRoutes.js');
//tell express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//mouting our routers
app.use('/', mainRouter);
app.use('/todo',todoRoutes);
app.listen(3000);
console.log("Express server running on port 3000");
And the corresponding todoRoutes.js file is where I require the post method:
var express = require('express');
var todoRoutes = express.Router();
var todoList = []; //to do list array
todoRoutes.get('/', function(req, res) {
res.sendFile(__dirname + '/views/todo/index.html');
});
todoRoutes.get('/create', function(req, res) {
res.sendFile(__dirname + '/views/todo/create.html');
});
todoRoutes.get('/api/list', function(req, res) {
res.json(todoList); //respond with JSON
});
todoRoutes.get('/api/get/:id',function(req, res){
res.json(todoList[req.params.id]);
});
todoRoutes.post('/api/create', function(req, res){
console.log("Creating the following todo:", req.body.todo);
todoList.push(req.body.todo);
res.send({redirect: '/api/list'});
});
and here is the corresponding html file:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Todo List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action = "/api/create" method="post">
<div>
<label for="todo">Enter your new Todo:</label>
<input type="text" id="todo" name="todo">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
If I put a console.log("") in the POST function of the todoRoutes.js file it will not be displayed, indicating that the function does not even get executed.
Any help will be very much appreciated.
You need to POST to /todo/api/create, based on your current route handling:
<form action = "/todo/api/create" method="post">
I just started learning ReactJS and I can't seem to get the onClick handler to work.
I followed the Express.js application generator tutorial and ended up with the following code.
Can somebody please tell me what's wrong?
//app.js file
var express = require('express');
var path = require('path');
// routes
var launch = require('./routes/launch');
var app = express();
// view engine setup
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// attach url to routes
app.use('/', launch);
//launch.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('launch', {});
});
module.exports = router;
//launch.jsx code
var React = require('react');
var DefaultLayout = require('./layouts/default');
// bootstrap
import {Button, Grid, Row, Col, Clearfix, Image, FormGroup, InputGroup, FormControl} from 'react-bootstrap';
var LaunchView = React.createClass({
render: function() {
return (
<FormGroup>
<InputGroup>
<FormControl id="launch-email" type="email" placeholder="Email" />
<InputGroup.Button>
<Button id="launch-submit" className="button-green" onClick={this.handleSubmit}>Submit</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
);
},
handleSubmit: function(){
alert("woot");
}
});
module.exports = LaunchView;
doesn't support attaching events on the client-side or doing client-side updates afterwards.
https://github.com/reactjs/express-react-views/issues/2
You can implemented a small "hack" and insert a script file which explicitly sets element's onclick behavior. Keep in mind that DOM has to be loaded in order to attach events.
let myElement = document.getElementsByClassName("overlay")[0];
myElement.addEventListener('click', () => {myElement.style.display = 'none';});
It's not elegant, but it works.