I can set file upload path to /fileupload1 folder, but how to set file upload path to /fileupload2 folder?. Thanks
myapp
/config
config.js
express.js
/fileupload1
/public
/fileupload2
server.js
In server.js :
var express = require('express'),
fs = require('fs'),
var app = express(),
app.use(express.static(__dirname + '/public'));
exports = module.exports = app;
In express.js :
var express = require('express'),
module.exports = function(app, config) {
app.use(express.static(config.root + '/public'));
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + "/fileupload1" }))
};
Try this:
express.bodyParser({
keepExtensions: true,
uploadDir : __dirname + "/../public/fileupload2"
})
Related
Here is my express code:
const express = require('express');
const serveStatic = require('serve-static');
const path = require('path');
// create the express app
const app = express();
var cors = require('cors');
app.use(cors());
app.use("/",serveStatic ( path.join (__dirname, '/dist') ) );
app.use('/static', express.static(path.join(__dirname, '/dist23')));
app.listen(port, () => {
console.log("listening on "+port)
});
The above code only works for the folder /dist. But when I go to /static, it shows a blank page and this error in the console:
If I put the js files from /dist23 into /dist, then /static works and shows me the application. Its almost like it is looking for files inside /dist and not /dist23. How do I fix it?
Both apps were built using vue-2.6.11. Both directories have files built/bundled for production.
You need to set the content type while serving your static files.
app.get('/index.html', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
app.get('/', (req, res) => {
res.set('content-type', 'text/plain').sendFile('index.html', { root: path.join(__dirname, 'public/dist/') })
});
Hey guys so I have the following in my app.js file
const express = require("express");
const app = express();
const path = require('path');
const hbs = require("express-handlebars");
app.engine(
"hbs",
hbs({
extname: "hbs",
//defaultLayout: "layout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
I also have a file located in server/views/layouts/ that is a handle bars file called share.hbs
I also have a file in my server/api/media.js that looks like this
const express = require("express");
const router = express.Router();
const database = require("../db");
router.get("/share", async (req, res, next) => {
res.render("share");
});
But when ever I try to render the file it errors out with the following error
Had to move my file out of the layouts folder and add this to the res.render call
res.render("share.hbs", { layout: "share" });
I have the following output section specified in my webpack.config.js:
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/'
},
I then have my express server set up like this:
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const config = require('./webpack.config.dev');
const app = express();
const compiler = webpack(config);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 4040;
const serverConfig = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true},
publicPath: '/'
};
app.use(express.static(__dirname + '/public'));
app.use(require('webpack-dev-middleware')(compiler, serverConfig));
app.use(require('webpack-hot-middleware')(compiler));
const indexFile = path.join(__dirname, './client/public/index.html');
app.use(express.static(__dirname + './build'))
app.get('*', function(req, res) {
console.log(req.originalUrl);
res.sendFile(indexFile);
});
app.listen(4040, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:4040');
});
When I am at the root url, i.e. '/' then the bundle.js file is rendered:
<script src="bundle.js"/>
But when I navigate to a non root url and refresh the page, webpack does not render the bundle.js and the script tag is not added.
By default only the root serves index.html. You need to enable historyApiFallback in your dev server config historyApiFallback: true. That way the server will serve index.html in all routes.
Turns out this more convoluted because I am using the HtmlWebpackPlugin, this fixes it:
var express = require('express');
var app = express();
var webpack = require('webpack');
var path = require('path');
var compiler = webpack(require('./webpack.config.js'));
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: '/'
}));
app.use('*', function (req, res, next) {
var filename = path.join(compiler.outputPath,'index.html');
compiler.outputFileSystem.readFile(filename, function(err, result){
if (err) {
return next(err);
}
res.set('content-type','text/html');
res.send(result);
res.end();
});
});
app.listen(3000);
I'm getting the hang of Node.JS/Express.JS plus Stylus, but I have a problem. I tried a lot of things but stylus just wont compile my CSS. I googled it, stackoverflowed it, none of the solutions worked. I guess I'm missing something trivial or looking at the wrong angle. Can you help me out fix stylus to autocompile my css upon PUG template rendering?
Here is ths server.js:
(function initialize(){
//TODO: set dependencies
var express = require('express');
var http = require('http');
var util = require('util');
var stylus = require('stylus');
var image = require('./routes/image');
//TODO: set variables and constants
var port = 8080;
var hostname = 'localhost';
//TODO: create express
var app = express();
//TODO: setup the template engine
app.set('views', './views');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(stylus.middleware({
src: __dirname + '/resources',
dest: __dirname + '/public',
debug: true,
force: true
}));
//TODO: set the default GET route
app.get('/', image.snatch);
//TODO: create the server
var server = http.createServer(app);
//TODO: start the server
server.listen(port, hostname, function start(){
console.log(util.format('Server is running at http://%s:%s/', hostname, port));
});
}());
Here is the image.js:
var snatchImage = function (req, res){
var html = res.render('snatchImage',
{
title: 'Hey',
message: 'Hello there!'
});
return res.send(html);
};
exports.snatch = snatchImage;
This is the PUG file:
doctype html5
html
head
title= title
link(rel='stylesheet', href='/css/style.css')
body
div(rel='stylesheet', href='/style.css', class="selection")= message
If I missed something here is the git, maybe it will be more clear to view it like that. Git link.
I am facing this error in my Expressjs file . Here is my code. I tried to set it according to this link
https://github.com/expressjs/multer/issues/169 But I am unable to correct this. Kindly help me out.
/**
* Express configuration
*/
'use strict';
var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var multer = require('multer');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
module.exports = function(app) {
// var env = app.get('env');
var env = 'development';
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(multer({
dest: '../client/assets/images/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file, req, res) {
console.log(file.fieldname + ' uploaded to ' + file.path);
var fileimage = file.name;
req.middlewareStorage = {
fileimage: fileimage
}
}
}));
app.use(cookieParser());
app.use(passport.initialize());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({
mongooseConnection: mongoose.connection
})
}));
if ('production' === env) {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', config.root + '/public');
app.use(morgan('dev'));
}
if ('development' === env || 'test' === env) {
// app.use(require('connect-livereload')());
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'client')));
app.set('appPath', 'client');
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
};
check your multer version as there was a syntax change in how to use multer.
now you have to define something as follows
var upload = multer({.....})
then use upload as your middleware in the express route.