I created a Glitch project and I want to upload files to it via user input. I am using express-fileupload and I followed the sample code from their docs to upload a file, but I keep getting an error. I think it might have to do with the directory I am using to move the file to. I have tried using '/app/views/uploads' and 'uploads/' as well as '/assets' (I used assets.js to do so) and I haven't been able to store the file. Here's my code:
var express = require('express');
var fileUpload= require('express-fileupload');
var app = express();
var assets = require("./assets");
app.use("/assets", assets);
app.use(express.static('views'));
app.use(fileUpload());
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get("/", function (request, response) {
response.render('index');
});
app.get('/fileupload', function(req, res) {
res.render('upload');
});
app.post('/upload', function(req, res) {
var sample= req.files.sample;
sample.mv('/assets', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
var listener = app.listen(process.env.PORT, function () {
console.log('SERVER STARTED ON PORT ' + listener.address().port);
});
The file is received succesfully, so the file not being there is not why I get errors.
I normally get this as the error:
{"errno":-13,"code":"EACCES","syscall":"open","path":"/assets"}
If you know where to upload the files to, please let me know. Any help would be very appreciated!
Related
Thanks for help in advance. I am getting following state from my console See Server running console log. Below Snippet is my app.js code where express and node server running. If you see my socket code my console.log underneath socket connection is not showing in server logs. Socket is not listening my messages.
I have also upload my sample of code at github, here you can find that (github.com/ferozpuri/node-app) client socket code is in SocketController.js an Angular controller file.
Here is my app.js file code, As you can see console log for "Connection was made" never show. and same with socket console.
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding 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.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
io.on('connection', function (socket) {
console.log('A connection was made!');
socket.on('chat.message', function (message) {
console.log('New Message : ' + message);
});
});
module.exports = app;
I am not getting socket response from node server. PLease let me know if i not explain this properly or any thing is not here.
Server listing on port you can see this in screenshort or my project structure
Project structure & app listening port OR NPM START CODE
You have set up all handlers but you did not initialize app.
http.listen(app.get('port'), function() {
console.log('App is listening on port', app.get('port'));
});
You did not start your server. In your code, your server is created with this line:
var server = require('http').Server(app);
So, sometime after that, you need to add:
server.listen(80); // or use whatever port number you want the server on
I have resolved this issue by adding following line of code under constructing my express/after var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
#jfriend00 and #Sablor, Thanks both of you for show me right direction. my server already running on port "3000" so with port 80 its was not working. because it is conflicting with my XAMPP server. Thanks you guys for participating
Trying to set up a basic Express server with a basic pug template.
Can you please tell me what I'm doing wrong here?
'use strict';
//Require Express
var express = require('express');
var app = express();
//Require Pug
var pug = require('pug');
//Require Twitter
var Twitter = require('twitter');
//Set view engine to serve middleware
app.set('view engine', 'pug');
//Set where to look for templates
app.set('views', __dirname + '/templates');
//Set up style sheets
app.use('/static', express.static(__dirname + '/public'));
//Access keys to access twitter account
var config = {
"consumerKey": "",
"consumerSecret": "",
"accessToken": "",
"accessTokenSecret": ""
};
//instantiate twitter client
var client = new Twitter(config);
//Log whether
var error = function (err, response, body) {
console.log('ERROR [%s]', err);
};
var success = function (data) {
console.log('Data [%s]', data);
};
//Set up server on Port 3000
app.listen(3000, function() {
console.log("The frontend server is running on port 3000!");
});
//Render when appropriate
//Tell app to render template
app.get('/'), function(req, res){
res.render('index', {title: 'Hey', message: 'Hello there!'});
}
I'm getting back The frontend server is running on port 3000! in the console.
What am I missing?
I'd really appreciate any help please
You're calling app.get() wrong. You're doing
app.get('/'), function(req, res){
...
Which is two statements separated by the comma operator. The correct syntax is to pass the function as the second argument:
app.get('/', function(req, res){
...
});
I know this question has been asked plenty of times before, and I've tried implementing those solutions, but they don't really work for me.
I have been tearing my hair out trying to figure out how to upload a file and read the file size through Node. I initially tried using the formidable npm, which seems to no longer be maintained as I can't find documentation on it. I had no way of dealing with the errors so I tried using multer. However, I repeatedly get an undefined log when I try to log req.file.
I have the server.js code below
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});
My javascript code with the AJAX call is provided below
$('#upload-butt').on('change', function(){
var file = $(this).get(0).files;
console.log(typeof file);
if(file.length > 0){
var formData = new FormData();
formData.append('Upload', file, file.name);
$.ajax({
url: '/upload',
type: 'POST',
data:formData,
processData:false,
contentType:false,
error: function(jXhr, status){
console.log('error: '+status);
},
success: function(data){
console.log('upload successful: '+data);
}
})
}
});
My index.jade code is given below
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
div(id="submit-button")
form(action = '/submit')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
I am ready to tear my hair out, so I will be very grateful to anyone who can help me here! Thanks!
You have not applied middle correctly.
You can use something like this:
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}))
You can access the fields and files in the request object:
console.log(req.body)
console.log(req.files)
So similarly in ur code you have to apply
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(upload);
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});
You're submitting a different <form> than the one with the image, the correct way is to place all content in a single <form>. This way you're submitting the form which includes the file.
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
This should work, for the jade part.
(docs about multer)
hi i'm trying to push code from my html file into my javascript file using buffers, toString, and readFileSync. I have a javacript file named index.js and a html file named index.html. This is the error on my site :
https://secret-ocean-5221.herokuapp.com/
This is my JS:
var fs = require('fs');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(fs.static(__dirname + '/public'));
app.get('/', function(request, response) {
var buf = new Buffer(fs.readFileSync("index.html"), "utf-8");
response.send(buf.toString);
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
my HTML simply says:
Welcome to my site.
You are not calling the toString method, only passing it in. Change to:
response.send(buf.toString());
Also, static is a property of express, not fs.
app.use(express.static(__dirname + '/public'));
With that, assuming your index.html file is in public, you don't need the fs.readFileSync at all.
It would also be more idiomatic to call readFile and use the node callback so it is non-blocking.
app.get('/', function(request, response, next) {
fs.readFile("index.html", function (err, fileBuffer) {
if (err) {
return next(err); // Tell express to handle errors
}
response.send(fileBuffer.toString());
});
});
I found the problem.
(1) I did not push my html file into my github repo
(2) My code was wrong here is the right code :
var express = require('express');
var fs = require('fs');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
fs.readFile('index.html', function(err, data){
response.send(data.toString());
});
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
I'm learning node.js and I have an error serving public CSS files to one URL.
It works with almost every pages, I go on the page and the css file is loaded from 127.0.0.1/css/style.css.
When the URL is 127.0.0.1/project/idProject it tries to get the css file from 127.0.0.1/project/css/style.css.
// INCLUDE MODULES =======================================================
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(express.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash())
// ROUTES =======================================================
// Set authentication variable
app.use(function (req, res, next) {
app.locals.login = req.isAuthenticated();
next();
});
require('./app/routes.js')(app, passport);
//ERROR MANAGEMENT =======================================================
app.use(app.router);
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('errors/404.twig', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
/*app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('errors/500.twig', { error: err });
});*/
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
console.log("New connection");
});
// LISTEN SERVER =======================================================
server.listen(80);
Any idea on how to solve this ?
Regards !
I tried approach which I saw in the comments, and because it did not work for me, I am posting an answer that worked.
All .css files are static, so you have to serve them to the client. However, you do not serve static files as a express middleware. Therefor you have to add them.
app.use(express.static(__dirname, 'css'));
Hi it was a problem for me to solve this, but with the help of salvador it was posible.
The only thing that im going to put is all the code and the you make the reference in the html, you only need to put the file not the folder in the html file.
//The index.js code
var express = require('express');
const path = require ('path');
//app va a ser mi servidor.
var app = express();
app.set('port', 3000)
//app.use(express.static('./public'));
//app.use(express.static( 'css'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'css')));
app.listen(app.get('port'), () => {
console.log('localhost:3000')
} );
this is the structure