req.files keeps returning undefined - javascript

req.files keeps returning undefined. I've tried connect-multiparty, body-parser, and express-fileupload. How do I make it work using express-fileupload and not multer?
here's my frontend:
<form action="/api/upload" method="post">
<label for="imgHere">file:</label>
<input type="file" id="imgHere" name="imgHere"><br><br>
<input type="submit">
</form>
I've checked using inspect element network tab, its sending the image just fine.
here's my backend:
const express = require("express");
const app = express();
const fileUpload = require("express-fileupload")
app.use(fileUpload())
app.post('/api/upload', function(req, res) {
console.log(req.files) // logs undefined
res.send("uploaded.")
});
app.listen(80, function()
{
console.log("Server loaded.")
});
How do I fix this?

You need to specify proper enctype as form attribute as well, like this:
<form action="/api/upload" method="post" enctype="multipart/form-data">
<label for="imgHere">file:</label>
<input type="file" id="imgHere" name="imgHere"><br><br>
<input type="submit">
</form>

Related

Form is not submitting in node

I am trying to make a post request from a html form and cant figure out where im going wrong.
> <form action="/api" method="POST">
<label for="username">username or email address</label>
<input name="username" id="username" type="text">
<label for="password">password</label>
<input id="password"name="password" type="text">
<button >Log in</button>
</form>
here is my main javascript file for the html (not the server)
"use strict"
let options = {
headers:{
"Content-Type" : "application/json"
},
method: "POST",
}
// fetch("/api",options)
And here is my node js server
"use strict"
//Installing express
let express = require(`express`)
let app = express()
app.use(express.json())
//running the server
app.listen(3000,()=>{
console.log("server is running boi");
})
//Middleware to load the static content
app.use(express.static(`public`))
//Database stuff
let Datastore = require('nedb')
let db = new Datastore({ filename: 'database.db' });
db.loadDatabase()
db.insert({username:"sid", password:"westham"})
//Handler for any post requests made
app.post(`/api`,(req,res)=>{
console.log("request was made");
console.log(req.body);
})
Two Observations
No middleware found in your server.js file for handling form data,
use body-parser http://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true });
In your html form, if you're not submitting form with JavaScript then mentiod button type as submit
<button type="submit" >Log in</button>

POST request - Not working with Node and Express

I just started learning Node and Express for a simple project but for some reason I cannot get POST to work. My browser gives me an error: Cannot POST /
Any assistance with this issue is appreciated. Thank you.
My code is below:
let express = require("express")
let ourApp = express()
ourApp.use(express.urlencoded({ extended: false }))
ourApp.get("/", function(req, res) {
res.send(`
<form action='/' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
ourApp.post("/answer", function(req, res) {
if (req.body.skyColor.toUpperCase() == "BLUE") {
res.send(`
<p>Congrats, that is the correct answer.</p>
Back to homepage
`)
} else {
res.send(`
<p>Sorry, that is incorrect.</p>
Back to homepage
`)
}
})
ourApp.get("/answer", function(req, res) {
res.send("Are you lost there is nothing to see here.")
})
ourApp.listen(3000)
For the "/" route, the form you return should have action="/answer", not action="/"
Your other routes should stay the same, and pretty sure that should work.
ourApp.get("/", function(req, res) {
res.send(`
<form action='/answer' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
You are hitting wrong endpoint.
You should post to for example http://localhost:3000/answer.
And one more thing if you want to pass JSON data in body you need to use body-parser middleware.
https://www.npmjs.com/package/body-parser

NodeJS - socket.on doesn't appear to be called

I am using the Node.JS POST method to submit a form to my server. It is transmitted to the server fine; no problems occur at this stage. However, when I use io.emit with socket.io to transfer the data back to the client, nothing seems to happen client-side. Nothing is printed to the console and I'm getting no errors there or in Command Prompt (where I'm running the server from).
index.html:
<form id="schoolCreateForm" action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
</script>
app.js:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/createSchool', function(req, res) {
response = {
school_name: req.body.schoolName,
school_private: req.body.schoolPrivate,
entry_password: req.body.entryPassword
};
console.log(response);
res.sendFile(__dirname + '/client/index.html');
io.emit('updateSchool', response);
});
serv.listen(3000);
console.log("Server started on localhost://3000");
Does anyone know what's going on?
<form action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit" id="schoolCreateForm">Submit</button>
After submitting your form data it will reload your page, it means socket connection will be ended. If you want to see a response with socket make ajax.post request without reloading the page.
<form id="schoolCreateForm">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#schoolCreateForm').addEventListener('click',
function(e) {
e.proventDefault() // this line will not all to reload page after
/// submitting the
//form data
### writh you ajax request functionality here
})
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});

Express 4 Multer / req.body and res.json not defined

I'm trying to do a single image file + text fields upload with using Express 4.0 & multer 1.1.0. The image file itself correctly uploads to the right destination but I'm getting errors with the text field and response:
1) multer's req.body req.file objects are undefined if logged in console
2) res.json (and also res.send when tested) gets the error - TypeError: res.json is not a function at Object.handle)
multer is configured as follows using moment.js for dates, which is almost line-for-line from the multer Github documentation:
//standard express-generator server.js requires
//passport.js implementation
var multer = require('multer');
var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './public/photoUploads/' + moment().year() + moment().month());
},
filename: function(req, file, cb){
cb(null, req.user._id + moment().unix());
}
})
var upload = multer({storage:storage});
require('./app/routes.js')(app, passport); //passport login routes - will eventually move app.post into this file
app.post('/upload/photoData', upload.array('photo'), function(err, req, res) {
var title = req.body.title;
var description = req.body.description;
var photoURL = req.file.filename;
var jsonResponse = {
"title": title,
"description": description,
"photoURL": photoURL
}
console.log(jsonResponse);
res.json(jsonResponse);
});
And here is the client-side form
<form id="photo-data" method="post" action="/upload/photoData" enctype="multipart/form-data">
<div class="form-group">
<div class="modal-body">
<label for="image" class="control-label">Photo upload</label>
<input type="file" class="form-control" name="photo" id="photo-main">
<label for="caption" class="control-label">Title:</label>
<input type="text" class="form-control" name="title" id="photo-title">
<label for="long-text" class="control-label">Further description:</label>
<input type="text" class="form-control" name="description" id="message-text">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button id="submit-photo" type="submit" class="btn btn-primary">Upload</button>
</div>
</div>
</form>
What am I doing wrong?
The signature for error handlers in Express is (err, req, res, next) (4 parameters), but Express sees less 4 than parameters in your handler so it assumes you're adding a normal route handler. The problem is that the order of your route handler parameters is wrong, it should just be (req, res). That will fix your res.json() error.
For your file field, you're currently telling multer you're expecting multiple files, so in that case you will need to check req.files instead of req.file. If you used upload.single('photo') instead, you could use req.file.
As for the non-file fields, make sure they are in fact submitted to the server by checking the network request for the form submission with your browser's developer tools.

req.files is empty when trying to upload a file to server with node js

HTML:
<form action="/uploadpic" method="post" enctype="multipart/form-data">
<input type="file" data-clear-btn="true" name="image" id="new_pic" value="" placeholder="Choose File">
<input type="submit" value="Add" style="width:30%">
</form>
NodeJS:
app.post('/uploadpic', function(req,res) {
console.log(req.files);
console.log(req.body);});
I also use:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json())
app.use(express.bodyParser({uploadDir:'./uploads'}));
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
in the console I get:
{}
{}
i dont seem to understand what could be the problem here.. thanks !
var fs = require('fs');
app.post('/uploadpic', function(req,res) {
//req.files contains array of files iterate and get it
//if it has only one. it is like object
//here is the code for object
if (req && req.files) {
var contentType = req.files.file.type;
var fname = req.files.file.name;
var image_path = req.files.file.path;
fs.readFile(image_path, function (err, data) {
var data = data; //this is your data use this
})
}
})
BodyParser doesn't include file uploads. You need to use something like multer or multiparty.
Also express (4.0+) doesn't come bundled with middleware anymore, so you'll need to use bodyparser for POST requests.

Categories