Why is Multer req.file is undefined with this simple file upload? - node.js

Let me start off with :I've read through many similar topics, yet can't find the solution.
I just started a fresh react app, and copied the form from the express/multer documentation
<form action="http://localhost:5001/app-dev/us-central1/api/upload" encType="multipart/form-data" method="post">
<div className="form-group">
<input type="file" className="form-control-file" name="uploaded_file"></input>
<input type="text" className="form-control" placeholder="Number of speakers" name="nspeakers"></input>
<input type="submit" value="Get me the stats!" className="btn btn-default"></input>
</div>
</form>
And I have a firebase function running locally with an express app.
const upload = multer({dest: './'})
app.post('/upload', upload.single('uploaded_file'), function (req: any, res: any) {
console.log(req.file, req.body)
});
the request in the network call has these headers
req.file is undefined when logging.
Does anyone see the missing piece?
Thanks a lot
ps. I use the cors middleware to resolve CORS issues (& GET calls are working)

It should work. Here is a minimal working example:
app.js:
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: './' });
app.post('/app-dev/us-central1/api/upload', upload.single('uploaded_file'), function (req, res) {
console.log(req.file, req.body);
res.sendStatus(200);
});
app.listen(5001, () => console.log('Server started at http://localhost:5001'));
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="container">
</div>
<script type="text/babel">
(function () {
const e = React.createElement;
class Upload extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<form action="http://localhost:5001/app-dev/us-central1/api/upload" encType="multipart/form-data" method="post">
<div className="form-group">
<input type="file" className="form-control-file" name="uploaded_file"></input>
<input type="text" className="form-control" placeholder="Number of speakers" name="nspeakers"></input>
<input type="submit" value="Get me the stats!" className="btn btn-default"></input>
</div>
</form>
)
}
}
const domContainer = document.querySelector('#container');
ReactDOM.render(e(Upload), domContainer);
})()
</script>
</body>
</html>
Server logs:
Server started at http://localhost:5001
{ fieldname: 'uploaded_file',
originalname:
'Stack Exchange personalized prediction data 2020-12-21.json',
encoding: '7bit',
mimetype: 'application/json',
destination: './',
filename: 'af7fc0ae20d3404ada7273792db07dc9',
path: 'af7fc0ae20d3404ada7273792db07dc9',
size: 99765 } [Object: null prototype] { nspeakers: '23' }
Client logs:
npx http-server -p 3001 -c-1Starting up http-server, serving ./
Available on:
http://127.0.0.1:3001
http://192.168.31.128:3001
Hit CTRL-C to stop the server
source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/65308716

Related

NotSameOriginAfterDefaultedToSameOriginByCoep issue on TinyMCE

I'm trying to embed tinyMCE to my project and having this issue from browser console while initializing TinyMCE.
GET https://cdn.tiny.cloud/1/vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak/tinymce/5.10.3-128/themes/silver/theme.min.js net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200
and this
GET https://sp.tinymce.com/i?aid=vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak&tna=tinymce_cloud&p=web&dtm=1646981257782&stm=1646981257782&tz=Asia%2FSeoul&e=se&se_ca=script_load net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep
I used script tag to add the TinyMCE...
with those errors, Nothing shows on the screen where textarea should be.
When I make an HTML file and open it with the browser, it has no problem.....
I'm trying this on localhost and I have localhost on approved domains list of TinyMCE's dashboard.
here's my code.
first, here's my entire EJS file
postWrite.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>My Blog</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.nav-pills > .nav-item > .active {
color : white;
background-color : black;
}
</style>
<script src="https://cdn.tiny.cloud/1/(MY-API-KEY)/tinymce/5/tinymce.min.js" crossorigin="anonymous" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#mytextarea'
});
</script>
</head>
<body>
<header class="container">
<div class="d-flex flex-fill py-3 mb-4 border-bottom p-3">
<a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-decoration-none text-body">
<span class="fs-4 ms-3">HKJang's Blog</span>
</a>
<ul class="nav nav-pills">
<li class="nav-item"><a href="/" class="nav-link text-body" >About Me</a></li>
<li class="nav-item">Projects</li>
<li class="nav-item">Modify Index</li>
</ul>
<form class="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-2">
<input type="search" class="form-control form-control-dark ms-3" placeholder="Search..." aria-label="Search">
</form>
<form>
<button class="btn btn-dark my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</header>
<main class="container">
<form method="post">
<textarea id="mytextarea">Hello, World!</textarea>
</form>
</main>
<footer class="container">
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<script>
</script>
</body>
</html>
and the part that I'm having trouble on is
...
<script src="https://cdn.tiny.cloud/1/(MY-API-KEY)/tinymce/5/tinymce.min.js" crossorigin="anonymous" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#mytextarea'
});
</script>
...
...
<main class="container">
<form method="post">
<textarea id="mytextarea">Hello, World!</textarea>
</form>
</main>
...
this EJS file is rendered by controller.
projectController.js
const boardView = async(req, res) => {
res.render("boardView", {});
};
const postView = async(req, res) => {
res.render("postView", {});
};
const postWriteView = (req, res) => {
res.render("postWrite", {});
}
module.exports = {
boardView,
postView,
postWriteView
};
and finally, this is index.js file for my server
index.js
const express = require('express');
const app = express();
var bodyparser = require('body-parser');
const helmet = require('helmet');
const compression = require('compression');
const csp = require('helmet-csp');
const cors = require('cors');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true})); // bodyparser : post 방식 body parsing용 -> express 기본 탑재
app.use(express.json());
var corsOption = {
origin: 'localhost',
credentials:'true'
}
app.use(cors(corsOption));
app.use(helmet());
app.use(
csp({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self' 'sha256-uts7zrnGYAKZNfvBc7PYcShvKP4t10vo5qemd5Yp0lc=' https://cdn.jsdelivr.net/"],
scriptSrc: ["'self' 'unsafe-inline' https://cdn.jsdelivr.net/ https://cdn.tiny.cloud/1/vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak/tinymce/5/tinymce.min.js"],
imgSrc: ["'self' https://blogprojectbucket.s3.amazonaws.com/ https://blogprojectbucket.s3.ap-northeast-2.amazonaws.com"]
},
})
);
app.use(compression());
app.set('view engine', 'ejs');
//Routes
app.use('/', require('./routes/board'));
app.use('/api', require('./routes/api'));
app.use('/project', require('./routes/project'))
const PORT = process.env.PORT || 3000;
app.listen(PORT, console.log("Server start at port : "+PORT));
Btw, I've tried to open all CORS configuration by trying app.use(cors())
Please help!
So this is proper way to use TinyMCE if you're using an Express app:
https://www.tiny.cloud/docs/integrations/expressjs/
You have to npm install TinyMCE and use it.

Form submit with bootstrap and nodejs

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

Uncaught ReferenceError: io is not defined at index 40

var express= require("express")
var bodyParser=require("body-parser")
var app= express()
var http=require('http').Server(app)
var io=require('socket.io')(http)
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
var messages=[
{name:"rohit",message:"hello"},
{name:"rohan",message:"hi"},
]
app.get('/messages', (req,res) =>{
res.send(messages)
})
app.post('/messages',(req,res)=>{
messages.push(req.body)
io.emit('message',req.body)
res.sendStatus(200)
})
io.on('connection',(socket)=>{
console.log('user connected')
})
var server= app.listen(3010, () => {
console.log("Server is listening on port ",server.address().port)
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script>src="http://localhost:3010/socket.io/socket.io.js"</script>
</head>
<body>
<div class="container">
<br>
<div class="jumbotron">
<h1 class="display-4">Send Message</h1>
<br>
<input id ="name" class="form-control" placeholder="Name">
<br>
<textarea id ="message" class="form-control" placeholder="Message"></textarea>
<br>
<button id="send" class="btn btn-success">Send</button>
</div>
<div id="messages">
</div>
</div>
<script>
var socket=io() <!--io is not defined pls help to resove this issue thnks in advance-->
$(()=> {
$("#send").click(() =>{
var message={name: $("#name").val(),message: $("#message").val()}
postMessage(message)
})
getMessages()
})
socket.on('message',addMessages)
function addMessage(message){
$("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message} </p>`)
}
function getMessages(){
$.get("http://localhost:3010/messages",(data)=>{
data.forEach(addMessage);
})
}
function postMessage(message){
$.post("http://localhost:3010/messages",message)
}
</script>
</body>
</html>
This is the code for server.js and index.html respectively. My error:
io is not defined at index 40
I am new to node.js and try making a simple chat app. I know this is an error talked about a lot in here. But after a few posts found via google, it still didn't solve my problem.
use the CDN script
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

Angular.js (net::ERR_ABORTED 404 (Not Found))

MY server configuration file
const express=require('express');
const app = express();
const logger=require('./utils/logger');
const bodyParser=require('body-parser');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set("view engine","ejs");
app.use('/', require('./Routes/sellerRoutes'));
app.listen(process.env.PORT||1234, (err)=>{
if(err) {
console.log('An Error has occured', err);
logger.error('Server Not Start ',err);
}
else {
console.log("Server Started");
logger.debug('Server Started');
}
})
My Routing file
const seller=require('express').Router();
const logger=require('../utils/logger');
const adminUser=require('../Models/Userclass');
const password=require('../Models/Passchange');
const operations=require('../db/Helpers/sellerOperations');
seller.post('/change',(req,res)=>{
console.log('kkkkkkkkkkkkkk');
res.render('change');
var newPass=req.body.newPass;
console.log("New Password:::",newPass);
var confirmPass=req.body.confirmPass;
console.log('Confirm Password:::',confirmPass);
var passPanel=new password(newPass,confirmPass);
var pr=operations.findOneAndUpdate(passPanel);
pr.then(data=>{
console.log(data);
res.render('change',{newPass:data.newPass, confirmPass:data.confirmPass});
})
})
seller.post('/submit',(req,res)=>{
res.render('submit');
});
module.exports=seller;
MY ejs (Template Engine) file
<body class="section">
<h1><center>Password Change</center></h1>
<form method="POST" action="submit">
<% var newPass;%> <% var confirmPass; %>
<label for="">New Password:</label>
<input type="password" id="newPass" name="newPass" value="<%=newPass%>">
<div class="cnfrm">
<label for="">Confirm Password:</label>
<input type="password" id="confirmPass" name="confirmPass" value="<%=confirmPass%>">
</div>
<button id="chngepswd" class="btn btn-success">OK</button></a>
</form>
<br>
</body>
My Controller.js file
const app=angular.module('app', []);
app.controller('adminctrl', ($scope,$http,$q)=>{
var newPass=$scope.newPass;
var confirmPass=$scope.confirmPass;
$scope.dochange()=function(){
$http.post('http://localhost:1234/user').then((data)=>{
let defered = $q.defer();
console.log(data);
defered.resolve(data);
}),then((err)=>{
console.log(err);
defered.reject(err);
})
return defered.promise;
}
})
Index.html File
<!DOCTYPE html>
<html lang="en" ng-app='app'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Document</title>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../app.js"></script>
<script src="../js/controller.js""></script>
</head>
<style>
</style>
<body >
<div ng-controller="adminctrl">
<div>
<label for="">New Password</label>
<input type="text" name="newPass" id="newPass" ng-model="newPass">{{newPass}}<br>
<label for="">Confirm Password</label>
<input type="text" name="confirmPass" id="confirmPass" ng-model="confirmPass">{{confirmPass}}<br>
<button ng-click="dochange()">OK</button><br>
</div>
</div>
<br>
</body>
</html>
I am making the front end for my web application. I made index.html file in public folder and I have made an js folder in which I have an controller.js file. I have declared the source of .js file in script tag in HTML file.
But when I load the server it says controller is not found and I have installed bower package manager from which I have installed angular.js. My browser is not able to find neither the bower component in which there is my (angilar.min.js file) nor controller.js file.
It says
net::ERR_ABORTED 404 (Not Found) for every file and even for bower.

req.body returns undefinded after setting bodyParser urlencoded to extended as false

I am a newbee to nodejs . I have tried to create simple chat App. The req.body in my app.post seems to return undefinded even after setting my body-parser urlencoded ({extented:false}).can anybody walk me through this?!..thanks in advance
here is my code server.js for server side:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(express.static(__dirname))
var messages = [
{name:'Brue',message:'Hello Diana'},
{name:'Diana', message:'Hey Bruce.'} ]
app.get('/messages', (req,res) => {
res.send(messages) })
app.post('/messages', (req,res) => {
messages.push(req.body)
res.sendStatus(200)})
var server = app.listen(8080, (err,data) => {
console.log('The server runs on the port:', server.address().port) })
here is my client side code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Message App</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<br>
<div class="jumbotron">
<h1 class="display-4"> Send Message </h1>
<br>
<input class="form-control" type="text" placeholder="Name">
<br>
<textarea placeholder = "Message" class="form-control" id="mesage" cols="30" rows="10"></textarea>
<br>
<button id = "send" class="btn btn-success"> Send</button>
</div>
<div id="messages"></div>
</div>
<script>
$(() => {
$('#send').click(() => {
var message = { name: $("#name").val(), message: $("#message").val()}
postMessage(message)
})
getMessages() })
function addMessages(message){
$("#messages").append(`<h4>${message.name}</h4> <p> ${message.message} </p>`) }
function getMessages(){
$.get('http://localhost:8080/messages',(data) => {
data.forEach(addMessages); }) }
function postMessage(message){
$.post('http://localhost:8080/messages', message)
}
In your html, you misspelled your textarea's id. It is id="mesage" instead of id="message" with two 's'. And you never set the id of #name. Fix these.
<input class="form-control" id="name" type="text" placeholder="Name">
<textarea placeholder="Message" class="form-control" id="message" cols="30" rows="10"></textarea>
Makes sure that your variable, which u will send is valid. I recommend you to use the chrome debugger in these situations.

Resources