I have tried to make an api to upload files in express using multer middleware but the request.file is undefined.
the express code is given below,
const express = require("express");
var multer = require('multer');
const cors = require("cors");
var app = express();
app.use(cors({ origin: true }));
const multerMid = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024,
},
});
app.post('/saveFile', multerMid.single('dp'), (request,response)=>{
try{
var dp = request.file;
if(dp)
{
return response.send("file uploaded");
}
else{
return response.send("No file uploaded");
}
}catch(error)
{
return response.send(error.errorMessage);
}
});
exports.app = functions.https.onRequest(app);
No file uploaded
this is what I always receive when I post a file to the route using the following html.
<html>
<head>
</head>
<body>
<form action = "<server>/saveFile" method="post" enctype="multipart/form-data">
<input type="file" name="dp"/>
<input type="submit" value="Save">
</form>
</body>
</html>
I need to upload the file to file to firebase storage thats why I don't use a static storage location in the multer object,
I am stuck please help.
Here a middleware needs to be defined
app.post('/saveFile', multerMiddleWare, (request,response)=>{...});
const multerMiddleWare = (req, res, next) => {
multerMid(req, res,
(error) => {
if (!error) return next();
return next('error');
});
};
const multerMid = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024,
},
}).single('dp');
Related
when I submit the form to the Submit form button, everything works and the uploaded file is logged into the server console, but why does the Multipart: Boundary not found error occur when I click on Submit using fetch
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const multer = require("multer");
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./images");
},
filename: (req, file, cb) => {
cb(null, Date.now() + "--" + file.originalname);
},
});
const upload = multer({ storage: fileStorageEngine });
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.get("/", (req, res) => {
res.send(`
<form action="/push" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<button type="submit">Submit form</button>
<button onclick="send(event)" type="submit">Submit using fetch</button>
</form>
<script>
function send(event) {
event.preventDefault();
let formData = new FormData(event.currentTarget.parentElement);
fetch("/push", {
body: formData,
headers: {
"Content-Type": "multipart/form-data",
},
method: "POST",
}).then((data) => console.log(data));
}
</script>
`);
});
app.post("/push", upload.single("image"), (req, res) => {
console.log(req.file);
});
app.listen(3000);
I suppose you want to upload an image? to do so you will need to pass three parameter in your fetch request uri , type and name in your formdata. as an exemple :
fetch("/push", {
body: {uri :formData.uri ,
type: formData.type,
name: forData.name}
headers: {
"Content-Type": "multipart/form-data",
},
method: "POST",
}).then((data) => console.log(data));
}
I have 2 input type="file" on a single form and I want file from left input upload into "left" folder and right to "right"
but how could I know what file was uploaded from right or left input?
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const multer = require("multer");
app.get("/", (req, res) => {
res.send(`
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="left"/><br>
<input type="file" name="right" /><br>
<button type="submit">send</button>
</form>
`);
});
app.post("/upload", function (req, res, fields) {
const storage = multer.diskStorage({
destination: function (req, file, cb) {
if (true /*if from input name left*/) {
cb(null, "left");
} else {
//if from input name right
cb(null, "right");
}
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({
storage: storage,
}).fields([{ name: "left" }, { name: "right" }]);
upload(req, res, (err) => {
if (err) throw err;
});
});
app.listen(3000);
You are using an upload with fields like this const upload = multer({ storage: storage, }).fields([{ name: "left" }, { name: "right" }]);
and it is supposed for the field names to be identical to form-data appended values,
so all you need to do is to access the request files correctly like following:
for the 'left' file input you access the uploaded file with:
req.files['left'][0]
and for the 'right' file input you also can access it the same way:
req.files['right'][0]
[
I am trying to route in my project. I want that on clicking connect button the rooms page should get rendered. Home page is working fine but as soon I as click connect it shows Cannot GET /rooms/0b2636b5-c254-47f4-ade8-9e6b745a96d1.The code works fine when instead of routing to rooms it is on root url.
I am new to web development and I tried reading other questions on similar problem but couldn't understand.
Server side(Server.js):
const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const io = require('socket.io')(server);
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('home');
})
app.get('/rooms', (req, res) => {
res.redirect(`/rooms/${uuidV4()}`);
})
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
server.listen(3000);
Client Side(script.js)
const socket = io('/rooms');
const videoGrid = document.getElementById('video-grid');
var peer = new Peer(undefined, {
path: '/peerjs',
host: '/rooms',
port: '3000'
})
Navigation bar on home.ejs
<nav class="nav">
<li class="nav-link">
Connect
</nav>
room.ejs
<script>
const ROOM_ID = "<%=roomId%>"
</script>
<script src="/socket.io/socket.io.js" defer ></script>
<script src="script.js" defer></script>
Structure of file
public
-script.js
views
-home.ejs
-room.ejs
server.js
You're really close to it, just 1 mistake in this block:
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
It should be:
app.get('/rooms/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
Express documentation page here in case you need it (section Route parameters).
I want to send a file with axios, from my Vue.js to my Node.js,
but the req.file parameter is never filled, it's undefined
Here is the simplified code from my vue :
Inscription.vue :
<template>
<div class="main_content">
<h1>Inscription</h1>
<div><input type='file' #change='openFile'></div>
<button type='button' v-on:click="inscription" class="inscription">Inscription</button>
</div>
</template>
<script>
import Axios from 'axios';
export default {
data () {
return { selectedFile: null}
},
methods:{
openFile (event) {
this.selectedFile = event.target.files[0];
},
inscription () {
let fd = new FormData();
fd.append('avatarBase64', this.selectedFile);
Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', {avatarBase64: fd});
}
}
My simplified node.js application :
main.ts
import express from "express";
var cors = require('cors');
var bodyParser = require('body-parser')
const multer = require('multer')
const http = require('http');
const server = express();
server.use(cors({origin: true}))
server.use(bodyParser.json({limit: '50mb', extended: true}));
server.use(
bodyParser.urlencoded({
extended: true
})
)
server.post("/api/testUploadImage", upload.single('avatarBase64'), async (req: any, res: any) => {
// req.file is undefined PROBLEM THERE
});
const httpServer = http.createServer(server);
httpServer.listen(port);
try changing headers of axios with
'content-type': 'multipart/form-data'
I found out : i was sending this
Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', {avatarBase64: fd});
instead of this :
Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', fd);
change your multer version and try it agian
npm i multer#2.0.0-rc.2
and edit this:
Axios.create({baseURL: 'http://localhost:4444'}).post('/api/testUploadImage', fd);
I am brand new to Express and Node.js, trying to build server-rendered app which will display some data from API.
This is my code
app.js
var express = require("express");
var app = express();
var request = require("request");
var apiKey = '****************************';
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set('viewEngine', 'ejs');
const options = {
method: 'POST',
url: 'http://api.somethingsomething.com/content/search/v1?',
headers: {
'X-Api-Key': `${apiKey}`,
'Content-Type': 'application/json'
},
body: {
'queryString': 'pigs',
'resultContext' : {
'aspects' :['title','lifecycle','location','summary','editorial' ]
}
},
json: true
}
app.get('/', function(req, res) {
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.stringify(body);
console.log(info);
res.render('index', { results: info}); // this does not render anything
}
})
});
app.listen(3000, function() {
console.log("Listening on port 3000");
})
index.ejs
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="searchResults">
<%= results %>
</div>
</body>
</html>
It does not render index.ejs and cannot display data.
Error: No default engine was specified and no extension was provided.
I tried googling it, but no luck. Any help will be appreciated; Thank you
problem was simple app.set('viewEngine', 'ejs'); was wrong, should be pp.set('view engine', 'ejs');