How to post an image using node js - node.js

Hi I've been trying to understand how to post an image using node js and here is my js file code..
I have an ejs file with me alongside this js file,
but as I run this code through the terminal, I get this message in my terminal.
/Users/thinking_nyum/Desktop/multiplemoon/app.js:9
filename: function(req, file, cb){
^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
Does this simply mean that I have a spelling error in my codes? Or do I have corrupted files in my node folder?
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const path = require('path');
// Set Storage engine
const storage = multer.diskStorage({
destination: './public/uploads/'
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
//Init uploads
const upload = multer({
storage: storage
}).single('myImage');
//Init app
const app = express();
//ejs
app.set('view engine', 'ejs');
//Public Folder
app.use(express.static('./public'));
app.get('/', (req, res) => res.render('index'));
app.post('/upload', (req, res) => {
res.send('test');
});
const port = 3000;
app.listen(port, () => console.log(`Server started on port ${port}`));
I will attach my ejs file on this page too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta hettp-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<title>Node File Uploads</title>
</head>
<body>
<div class="container">
<h1>File Upload</h1>
<%= typeof msg != 'undefined' ? msg : '' ; %>
<form action="/upload" method"POST" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn grey">
<span>File</span>
<input name="myImage" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn black">Send</button>
</form>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

Related

Node.js/Express post route failing

Trying out Node.js for the first time. My POST route is failing with "Cannot POST /admin/add-product.html". GET request is being served fine from the same route. I have had a look around here. Several answers to similar issues but nothing is helping. Here is my code:
./index.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const adminRoutes = require('./src/routes/admin');
const shopRoutes = require('./src/routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.listen(3000);`
./src/routes/admin.js
const path = require('path');
const express = require('express');
const router = express.Router();
// served on /admin/add-product GET route
router.get('/add-product', (req, res, next) => {
res.sendFile(path.join(__dirname, '../', 'views', 'add-product.html'));
});
// served on /admin/add-product POST route
router.post('/add-product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
// res.send('<h1>product saved</h1>');
});
module.exports = router;
./src/views/add-product.html
<!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>Add Product</title>
</head>
<body>
<header>
<nav>
<ul>
<li>Shop</li>
<li>Add Product</li>
</ul>
</nav>
</header>
<main>
<form action="/admin/add-product.html" method="POST">
<input type="text" name="title" /><button type="submit">
Add Product
</button>
</form>
</main>
</body>
</html>
Thank you!!!
The action in the form need to match the route declare in the NodeJS application, it should be :
<form action="/admin/add-product" method="POST">
Remove the .HTML from the action attribute of the form.

Why empty req.body on POST request in expressjs?

I am new to expressjs. I am sending data from a web form to another form(or show on console) with the POST request. But I am receiving a empty object. My routes are in separate folder where i handling the data. I used body-parser as middleware for handling the request body.
This is a simple webform
<!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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<title>Login</title>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Login</h1>
</div>
<form method="POST" class="col-md-8" action="/profile">
<div class="form-group row">
<div class="col-md-4">
<label for="email" class="form-control border-0">Email</label>
</div>
<div class="col-md-8">
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
</div>
<div class="form-group row">
<div class="col-md-4">
<label for="password" class="form-control border-0">Password</label>
</div>
<div class="col-md-8">
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
This is the route file(route.js)
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json(); // support json encoded bodies
var urlencodedParser = bodyParser.urlencoded({ extended: false }); // support encoded bodies
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/login', (req, res)=>{
res.render('auth/login');
});
router.post('/profile', urlencodedParser, function(req, res){
res.send("THank you");
console.log("called post");
console.log(req.body);
});
module.exports = router;
This is app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json(); // support json encoded bodies
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
You need to put name attribute to HTML <input> tag, for ex:
<input name="email" type="email" class="form-control" id="email" placeholder="Enter email">

Multer while getting error " transfer-encoding' of undefined"

HTML
<!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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<title>Node file uploads</title>
</head>
<body>
<div class="container">
<h1>File upload</h1>
<%= typeof msg!= 'undefined' ? msg: ''%>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn grey">
<span>File</span>
<input name="myImage" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</body>
</html>
NODEJS CODE
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const path= require('path');
const bodyParser = require('body-parser');
const app = express();
// middle ware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//set storage engine
const storage = multer.diskStorage({
destination: './public/uploads/',
filename:(res,file,cb)=>{
cb(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname));
}
});
// init app
const upload = multer({storage:storage}).single('myImage');
const port = 3000;
// ejs
app.set('view engine','ejs');
//public folder
app.use(express.static('./public'));
// routing
app.get('/', (req,res)=>{
res.render('index');
});
app.post('/upload',(req,res)=>{
upload(res,res,(err)=>{
if(err){
res.render('index',{msg:err});
res.send('error uploading');
}else{
// console.log(req.file);
res.send('test');
}
});
});
app.listen(port,()=>{
console.log('server is connected at '+ port);
});
Error
TypeError: Cannot read property 'transfer-encoding' of undefined
at hasbody (/var/www/html/nodeuploads/node_modules/type-is/index.js:93:21)
at typeofrequest (/var/www/html/nodeuploads/node_modules/type-is/index.js:127:8)
at multerMiddleware (/var/www/html/nodeuploads/node_modules/multer/lib/make-middleware.js:18:10)
at app.post (/var/www/html/nodeuploads/app.js:40:4)
at Layer.handle [as handle_request] (/var/www/html/nodeuploads/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/html/nodeuploads/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/html/nodeuploads/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/html/nodeuploads/node_modules/express/lib/router/layer.js:95:5)
at /var/www/html/nodeuploads/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/var/www/html/nodeuploads/node_modules/express/lib/router/index.js:335:12)
When i click submit button below message is displayed
transfer-encoding' of undefined
Please let me know if additional details are required for debugging this issue
Thanks

NodeJs - route parameters crash the file system on a client

This is my server
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const handlebars = exphbs.create({
defaultLayout: 'index',
extname: 'hbs'
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
require('./Server/Routes/questionnaire')(app);
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'Public')));
app.listen(8888, function () {
console.log('Server running on port 8888');
});
and I use this route
module.exports = function (app) {
app.get('/questionnaire', function (req, res) {
res.render('questionnaire', {
eventInfo: {
description: "TEST",
imgHost: "Resources/img_logo.png"
}
});
});
};
the code works fine. When adding a parameter to the route /questionnaire/:id no css files or client code is found.
What am I missing? Using a parameter in my route should have the correct syntax. This error just appears, when using parameters in the routes.
EDIT:
The whole directory
First I use my default HTML index.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<link href="Style/base.css" rel="stylesheet">
<link href="Style/header.css" rel="stylesheet">
<link href="Style/button.css" rel="stylesheet">
<link href="Style/input.css" rel="stylesheet">
<link href="Style/link.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="Client/header.js"></script>
<body>
<div id="header">
</div>
{{{body}}}
</body>
</html>
and I render my questionnaire.hbs template
<link href="Style/Templates/questionnaire.css" rel="stylesheet">
<script src="Client/Templates/questionnaire.js"></script>
<div id="content">
</div>
As mentioned in the comments, I have to write /....
When using a parameter, it seems I have to write full paths like
"/Resources/img_logo.png"
instead of
"Resources/img_logo.png"
Try this in your app.js
//comment this line
//app.use(express.static(path.join(__dirname, 'Public')));
//add this middleware
app.use(express.static('./Public'));
app.use('/Style',express.static('./Public/Style'));
app.use('/Client',express.static('./Public/Client'));

net::ERR_CONNECTION_REFUSED socket.io

i'm trying to have a socket working on my sever
here is my app.js file
console.log('app.js says hi');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
and my index.html file
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
</script>
</body>
</html>
and in the console log I get this error:
GET http://localhost:4200/socket.io/?EIO=3&transport=polling&t=LsOF2yq net::ERR_CONNECTION_REFUSED
i found it
replace this line
var socket = io.connect('http://localhost:4200');
with
var socket = io.connect('http://yourdomain.com:4200');

Resources