gulp inject not working properly - node.js

I am using gulp inject command to add my css and js files to the html page. When I am checking the file the file are injected but when I run the html page it shows file not found and it doesn`t load the files.
This is gulp file -
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var nodemon = require('gulp-nodemon');
var jsFiles = ['*.js','src/**/*.js'];
gulp.task('style',function(){
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish',{
verbose: true
}));
});
gulp.task('inject',function(){
var wiredep = require('wiredep').stream;
var inject = require('gulp-inject');
var injectSrc = gulp.src([__dirname + '/public/css/*.css',__dirname + '/public/js/*.js'],{read: false});
var injectOptions = {
ignorePath: '../..public'
};
var options = {
bowerJson: require(__dirname + '/node_modules/bower/lib/node_modules/qs/bower.json'),
directory: './public/lib',
ignorePath: '../../public'
}
return gulp.src('./src/views/*.html')
.pipe(wiredep(options))
.pipe(inject(injectSrc,injectOptions))
.pipe(gulp.dest('./src/views'));
});
gulp.task('serve', ['style','inject'], function(){
var options = {
script: 'app.js',
delayTime: 1,
env:{
'PORT': 3000
},
watch: jsFiles
}
return nodemon(options)
.on('restart',function(ev){
console.log('Restarting....');
})
})
This is my app.js -
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
//app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/src/views'));
app.get('/',function(req,res){
res.send('Hello World');
});
app.get('/books',function(req,res){
res.send('Hello Books');
});
app.listen(port,function(err){
console.log('running server on port'+ port);
});
But still files not getting loaded on my html page.
Can anyone help me in understanding what the problem is?
Files injected in html page:

Fixed the issue.
changed the line-
var injectOptions = {
ignorePath: '../..public'
};
to this-
var injectOptions = {
ignorePath: '/public'
};

Related

api route not working over https

I have a node server running on port 3000 to serve api request.
this works fine...
http://www.skoolaide.com:3000/api/accounts
this does not.
https://www.skoolaide.com:3000/api/accounts
Can someone tell me why? If you go to https://www.skoolaide.com, the ssl cert is configured correctly, but do I need to do something on the node side?
this is my server js file. Please note: is only runs the middleware(api) on port 3000. For some reason I cannot access the middleware via https...
'use strict';
var express = require('express');
var router = express.Router();
var app = express();
var http = require('http');
var open = require('open');
var cors = require('cors');
var path = require('path');
var morgan = require('morgan');
var errorhandler = require('errorhandler');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./config/config');
var jwt = require('jsonwebtoken');
var compression = require('compression');
var runMiddleware = require('run-middleware')(app);
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var multer = require('multer');
var node_xj = require("xls-to-json");
var moment = require('moment');
var async = require('async');
var btoa = require('btoa');
var sharp = require('sharp');
var students = require("./middleware/students.api");
var accounts = require("./middleware/accounts.api");
var messages = require("./middleware/messages.api");
var advocates = require("./middleware/advocates.api");
var authenticate = require("./middleware/authenticate.api");
var email = require("./middleware/email.api");
var text = require("./middleware/text.api");
var colleges = require("./middleware/colleges.api");
var amazon = require("./middleware/amazon.api");
var rewards = require("./middleware/rewards.api");
var files = require("./middleware/files.api");
var validations = require("./middleware/validations.api");
var points = require("./middleware/points.api");
var notifications = require("./middleware/notifications.api");
var notificationsMap = require("./middleware/notificationsMap.api");
var trivia = require("./middleware/trivia.api");
var tasks = require("./middleware/rewardgoals.api");
var classes = require("./middleware/classes.api");
var connections = require("./middleware/connections.api");
var badges = require("./middleware/badges.api");
var fixpasswords = require("./middleware/fixpasswords.api");
var Files = require('./models/files');
mongoose.connect(config.database);
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
app.set('uploads', path.join(__dirname, 'uploads'));
app.get("/uploads/*", function (req, res, next) {
res.sendFile(__dirname + req.url);
});
var whitelist = ['https://www.skoolaide.com', 'https://skoolaide.com'];
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.headers['origin']) !== -1) {
corsOptions = { origin: true, credentials: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false, credentials: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use(cors(corsOptionsDelegate));
//this is used because the body parser removes undefined values from the database.
app.set('json replacer', function (key, value) {
// undefined values are set to `null`
if (typeof value === "undefined") {
return null;
}
return value;
});
app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
},
onFileUploadStart: function (file) {
//console.log(file.fieldname + ' is starting ...')
},
onFileUploadData: function (file, data) {
//console.log(data.length + ' of ' + file.fieldname + ' arrived')
},
onFileUploadComplete: function (file) {
//console.log(file.fieldname + ' uploaded to ' + file.path)
}
}).any());
// "files" should be the same name as what's coming from the field name on the client side.
app.post("/api/upload", function (req, res) {
//console.log(req.files[0].mimetype)
fs.readFile(req.files[0].path, function (err, data) {
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
if(req.files[0].mimetype.indexOf('image') > -1){
sharp(data)
.rotate()
.resize(800, 800)
.max()
.toFile(newPath, function(err, info){
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.avatarId = req.body.avatarId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
} else{
//not an image file...
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log('Writing file: ', newPath);
fs.writeFile(newPath, data, function (err) {
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log(readPath)
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.profileId = req.body.profileId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
}
});
});
app.use(express.static('www'))
var a = ['/'];
//all get requests resolve to index.
app.get(a, function (req, res) {
console.log('This is a test', req.originalUrl, req.url);
res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
res.setHeader('Judson', 'Rocks!');
if (req.originalUrl == '/') {
res.sendFile('www/index.html', {root: __dirname});
}
});
app.set("superSecret", config.secret)
//var upload = require("./middleware/upload.api");
app.use('/api', router);
app.use('/api/students', students);
app.use('/api/accounts', accounts);
app.use('/api/messages', messages);
app.use('/api/advocates', advocates);
app.use('/api/authenticate', authenticate);
app.use('/api/email', email);
app.use('/api/text', text);
app.use('/api/colleges', colleges);
app.use('/api/amazon', amazon);
app.use('/api/rewards', rewards);
app.use('/api/files', files);
app.use('/api/validate', validations);
app.use('/api/points', points);
app.use('/api/notifications', notifications);
app.use('/api/notificationsMap', notificationsMap);
app.use('/api/trivia', trivia);
app.use('/api/rewardgoals', tasks);
app.use('/api/classes', classes);
app.use('/api/badges', badges);
app.use('/api/connections', connections);
app.use('/api/fixpasswords', fixpasswords);
/**SERVER*************************************/
// all environments
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
// express/connect middleware
app.use(morgan('dev'));
app.use(compression()); //use compression
// development only
if ('development' === app.get('env')) {
app.use(errorhandler());
}
/**END SERVER*************************************/
var cluster = require('cluster');
if (cluster.isMaster) {
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for (var i = 0; i < numWorkers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function (worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(app.get('port'),
function () {
console.log('myApp server listening on port ' + app.get('port'));
});
}
Your code only starts an HTTP server. This line:
app.listen(app.get('port'))
starts only an http server. If you want support for HTTPS, you have to also start an HTTPS server and you have to start it on a different port. The express doc for app.listen() shows you how to do that and it's basicaly like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
where options contains your SSL certificates and where you fill in the desired port numbers for your http server and your https server.
If you were operating under the illusion that you don't need a port number in the browser in order to access both an http and https server, that's because the browser fills in a default port number for you. If you just type an http URL, it uses port 80. If you type an https URL with no port, it uses port 443. If you're not on those two specific ports, you have to specify the desired port in the browser URL. In either case, you need a separate server on separate ports for both http and https.
Use var https = require("https"); not
Var http = require ("http");

Cannot connect to Node.js server using socket.io + express + webpack, requests return 404 errors

I am trying to test my first socket.io server/client codes. But it failed.
My HTML file is like this:
<html>
<body>
<h1>Welcome to socket project</h1>
<div id="result"></div>
<script src="https://cdn.socket.io/socket.io-1.4.8.js"></script>
<script src="./dist/main.bundle.js"></script>
</body>
</html>
My client side code is like this:
const socket = io.connect('http://localhost:9999');
console.log('Connected: ', socket.connected);
socket.emit('setPlayerPosition', {
reason: 'It\'s my birthday'
});
My server code is like this:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.base');
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer();
const io = require('socket.io')(server);
const port = 9999;
const devPort = port - 1;
const domain = 'http://127.0.0.1:' + devPort;
const devServer = new WebpackDevServer(webpack({
devtool: 'eval',
entry: {
main: [
'webpack/hot/only-dev-server',
`webpack-dev-server/client?${domain}`,
config.entry.main
]
},
output: config.output,
plugins: config.plugins.concat([
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]),
module: config.module,
resolve: config.resolve,
}), {
publicPath: `${domain}/`,
hot: true,
historyApiFallback: true,
port: devPort,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
});
io.on('connection', function(socket) {
socket.on('setPlayerPosition', function(id, msg) {
console.log('Position' + msg.reason);
socket.broadcast.to(id).emit('serverMsg', {
msg: 'hello'
});
});
});
app.use('/static', express.static(__dirname + '/media'));
// app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.end(
fs.readFileSync('./public/index.html')
.toString()
.replace(/\.\/dist\//g, `${domain}/`)
);
});
app.listen(port, function() {
console.log('Server is running on port', port);
});
devServer.listen(devPort);
I can connect with http but when I use socket.io it gives me a 404 error.
Failed to load resource: the server responded with a status of 404 (Not Found), the client side console log is "Connected: false".
How to resolve this problem?
You're creating an HTTP server to host the socket.io server:
const server = require('http').createServer();
const io = require('socket.io')(server);
However, you're not calling .listen() on that server instance, so it won't be listening on port 9999 as you might expect.
Here's an alternative setup that should work:
const port = 9999;
const app = express();
const server = app.listen(port, function() {
console.log('Server is running on port', port);
});
const io = require('socket.io')(server);

Start a proxy server with nodejs so that it serves requests preprended with "/wps_proxy/wps_proxy?url="

I want to start a proxy server with node.js so that it serves requests preprended with "/wps_proxy/wps_proxy?url=". I want it so I can use the wps-js library of north52 (check the installation tips) . I have already a server where I run my application.
What I did try until now is :
the server.js file
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require("path");
var app = express();
app.use(express.static(__dirname + '/' + 'public'));
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//****** this is my try ******************************
app.get('/wps_proxy/wps_proxy',function (req,res){
res.sendfile(__dirname + '/' + 'public/wps_proxy/wps-js/target/wps-js-0.1.2-SNAPSHOT/example.html');
if(req.query !== undefined){//because it enters sometimes without url
var http = require('http');
//Options to be used by request
var options = {
host:"geostatistics.demo.52north.org",//fixed given data
port:"80",
path:"/wps/WebProcessingService"
};
var callback = function(response){
var dat = "";
response.on("data",function(data){
dat+=data;
});
response.on("end", function(){
res.end(dat)
})
};
//Make the request
var req = http.request(options,callback);
req.end()
}
})
var ipaddress = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.set('port', port);
app.listen(app.get('port'),ipaddress, function() {
console.log( 'Server started on port ' + app.get('port'))
})
//***************************************
but its not working.. I think that the data are not sent back correctly..
This is a live example of what I want to do.. http://geoprocessing.demo.52north.org/wps-js-0.1.1/
and this is a live example of my application (check the console for errors) http://gws-hydris.rhcloud.com/wps_proxy/wps_proxy
I did find my answer from this post How to create a simple http proxy in node.js? so the way i solve it was:
app.get('/wps_proxy/wps_proxy',function (req,res){
var queryData = url.parse(req.url, true).query;
if (queryData.url) {
request({
url: queryData.url
}).on('error', function(e) {
res.end(e);
}).pipe(res);
}
else {
res.end("no url found");
}
})

File download is not working with nodejs gridfs

i'm uploading images to gridfs-stream using node and express..uploading is working fine but am unable to download
app.post('/upload', function (req, res) {
var tempfile = req.files.displayImage.path;
var origname = req.files.displayImage.name;
var _id = guid();
var writestream = gfs.createWriteStream({
filename: _id
});
// open a stream to the temporary file created by Express...
fs.createReadStream(tempfile)
.on('end', function () {
res.send(_id);
})
.on('error', function () {
res.send('ERR');
})
// and pipe it to gfs
.pipe(writestream);
});
app.get('/download', function (req, res) {
// TODO: set proper mime type + filename, handle errors, etc...
gfs
// create a read stream from gfs...
.createReadStream({
filename: req.param('filename')
})
// and pipe it to Express' response
.pipe(res);
});
the above code is unable to download the image by this cmd download?filename=acf58ae4-c853-f9f3-5c66-c395b663298a
You might need to check your values in params. But hopefully this near minimal sample provides some help:
Update
And it has helped, because it highlights that you are looking up the _id as a filename. Instead you should be doing this:
.createReadStream({
_id: req.param('filename')
})
if not
.createReadStream({
_id: mongoose.Types.ObjectId(req.param('filename'))
})
Since the _id field is different to the filename
app.js
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var conn = mongoose.createConnection('mongodb://localhost/mytest');
conn.once('open', function() {
console.log('opened connection');
gfs = Grid(conn.db);
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
routes/index.js
exports.index = function(req, res){
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({
filename: 'receptor.jpg'
}).pipe(res);
};

Express socket.io formidable mean.io stuck how to integrate in form progress

I'm working on a mean.io
server.js
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
fs = require('fs'),
passport = require('passport'),
logger = require('mean-logger');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
//Load configurations
//Set the node enviornment variable if not set before
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
//Initializing system variables
var config = require('./config/config'),
auth = require('./config/middlewares/authorization'),
mongoose = require('mongoose');
//Use only for development env
if (process.env.NODE_ENV === 'development') {
//mongoose.set('debug', true);
}
// set temp directory for uploads
process.env.TMPDIR = config.tmp;
//Bootstrap db connection
var db = mongoose.connect(config.db);
//Bootstrap models
var modelsPath = __dirname + '/app/models';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(newPath);
}
} else if (stat.isDirectory()) {
walk(newPath);
}
});
};
walk(modelsPath);
//bootstrap passport config
require('./config/passport')(passport);
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
//express settings
require('./config/express')(app,passport,db);
//Bootstrap routes
require('./config/routes')(app,passport,auth);
//Start the app by listening on <port>
var port = process.env.PORT || config.port;
server.listen(port);
io.sockets.on('connection', function (socket){
socket.on('addPost', function (data) {
socket.broadcast.emit('addedPost', data);
});
});
console.log('Express app started on port ' + port);
//Initializing logger
logger.init(app,passport ,mongoose);
//expose app
exports = module.exports = app;
routes.js
var postController = require('../app/controllers/api/post');
app/controllers/api/post.js
exports.upload = function(req, res,next) {
var w = 200;
var h = 75;
var form = new formidable.IncomingForm;
form.on('progress', function(bytesReceived, bytesExpected){
var percent = Math.floor(bytesReceived / bytesExpected * 100);
// here is where you can relay the uploaded percentage using Socket.IO
// How can got socket here !
socket.emit('progress', { percent: percent });
});
form.parse(req, function(err, fields, files){
if(err){
res.jsonp(500, err.message);
}
});
};
I don't find the way to get socket
in exports.upload any ideas ?

Resources