I am trying to design a simple app to upload files to a server. The front-end uses AngularJS in a Jade view engine, the back-end is an Express server written in Nodejs.
I am using ng-file-upload, but the problem is that the Upload service provided by the file upload module requires a Url destination for the file to be uploaded at. No matter what I place in this destination, my app gives me a 404 error of not found. I have no idea how to provide a destination folder to ng-file-upload in a way that doesn't generate a 404 error.
Here is my controller for the upload:
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
$scope.f = file; //set the global scope file to 'file'
$scope.errFile = errFiles & errFiles[0]; //check if any invalid filed exist
if (file) { //check if a file was submitted
file.upload = Upload.upload({
url: 'http://localhost:3000/upload',
data: { file: file }
});
file.upload.then(
function(response) {
$timeout(function () {
file.result = response.data;
});
},
function(response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
},
function(evt) {
file.progress = Math.min(100, parseInt(100.0 * (evt.loaded / evt.total)));
}
);
}
}
}]);
Here is my jade template:
extends layout
block content
h1= title
button(type='file', ngf-select='uploadFiles($file, $invalidFiles)', accept='.csv')
| Select File to Upload
br
br
| File:
div(style='font:smaller')
| {{f.name}} {{errFile.name}} {{errFile.$error}} {{errFile.$errorParam}}
span.progress(ng-show='f.progress >= 0')
div(style='width:{{f.progress}}%', ng-bind="f.progress + '%'")
And my express server app.js, which includes multer as middleware:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb (null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb (null, (file.originalname + 'datetimestamp'));
}
});
var upload = multer({ storage: storage }).any();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
/*app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});*/
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));
app.use(express.static('../client'));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.post('/upload', function (req, res) {
upload(req, res, function(err) {
if (err) {
res.json({ error_code: 1, err_desc: err });
return;
}
res.json({ error_code: 0, err_desc: null });
});
});
module.exports = app;
Any idea how to give the angular module a server-side folder it can store the file in?
Related
I'm using express for the first time, and got some problem while uploading files. I've followed many tutorials but no one worked. I just got an empty page and no file is uploaded
index1.jade
doctype html
html(lang='en')
head
title
meta(charset='UTF-8')
body
form(role="form", action="/", method="post", enctype="multipart/form-data")
div(class="form-group")
label(for="onixfile") Upload ONIX File
input(type="file", name="onixfile", id="onixfile")
input(type="submit")
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var multer = require('multer');
var app = express();
var multer = require('multer');
var upload = multer({ dest: './uploads' });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
route/index.js
var express = require('express');
var multer = require('multer');
var router = express.Router();
var upload = multer({ dest: 'uploads/' });
/* GET home page. */
router.get('/', function(req, res) {
res.render('index1', { title: 'ONIX Validator' });
});
router.post('/upload', upload.single('file'), function(req, res){
var file = '/' + req.file.filename;
var fs = require('fs');
fs.open("./uploads",'r',function(err, fd){
fs.readFile(file ,function(err, data){
if(err) throw err;
fs.writeFile("./uploads/"+req.file.filename, data), function(err) {
if(err) {
console.log(err);
}else {
console.log("Done");
}
}
});
});
});
module.exports = router;
Do this in your route/index.js
var upload = multer({ dest: 'uploads/' });
router.post('/upload', upload.single('file'), function(req, res){
var file = '/' + req.file.filename;
var fs = require('fs');
fs.open("./uploads",'r',function(err, fd){
fs.readFile(file ,function(err, data){
if(err) throw err;
fs.writeFile("./uploads/"+req.file.filename, data), function(err) {
if(err) {
console.log(err);
}else {
console.log("Done");
}
}
});
});
});
This should upload the file to your applications file-system in the /uploads dir.
Make sure you have to place these html & js file into uploads folder in solution directory.check it out below code.
Index.html Code:
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" id="upload" name="submit">
</form>
Server.js Code:
var express = require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
var splitted = file.originalname.split('.');
var format = splitted[splitted.length - 1];
callback(null, file.fieldname + '-' + Date.now() + '.' + format);
}
});
var upload = multer({ storage: storage }).single('userPhoto');
app.get('/', function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post('/api/photo', function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Error uploading file.");
}
res.send("File is uploaded");
});
});
app.listen(3000, function () {
console.log("Working on port 3000");
});
I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
//app.get('/');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You need only 1 server(REST server). Just use node.js server.
Read it:
REST
I am new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js is :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.
I want to serve index.html in docs/ subdirectory of public folder as static file. The index file should be served both at /index.html and / URLs.
Below is my app.js code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Below is my routes.index code
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log("comes in");
//res.sendFile(path.join(__dirname, 'public/', 'docs/index.html'));
//res.sendFile('index.html', { root: path.join(__dirname, './public') });
res.sendFile('/docs/index.html');
});
When i run localhost:3000, it does not re-direct to /docs/index.html [static content]
Please try below code:
res.sendFile(__dirname + '/doc/index.html');
My code works fine on localhost. But when I push to heroku. I'm fairly new to node.js.
Here is my app.js file.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app).listen(process.env.PORT || 8080);;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var mongoose = require('mongoose');
var io = require('socket.io').listen(server);
var nicknames = [];
io.configure(function() {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
io.sockets.on('connection', function(socket) {
io.sockets.emit('usernames', nicknames);
socket.on('chat message', function(data) {
io.sockets.emit('chat message', {
msg: data,
nick: socket.nickname
});
});
socket.on('new user', function(data, callback) {
if (nicknames.indexOf(data) != -1) {
callback(false);
} else {
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
io.sockets.emit('usernames', nicknames);
}
});
socket.on('disconnect', function(data) {
if (!socket.nickname) return;
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
io.sockets.emit('usernames', nicknames);
});
});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
app.get('/', function(req, res) {
res.render('index.hjs');
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I get this error when I run the actual website.
Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments.
If you are the application owner, check your logs for details.
I'm creating a public chat but for whatever reason I cannot get the application running. How can I fix this problem?