Gulp-Connect-Php + browserSync + Gulp-Connect address in use issue - npm

I need an ability to use browserSync with php support and some specific url rewrites. I came up with browserSync with Gulp-Connect-Php packages plus Gulp-Connect + modrewrite.
Here is my config:
var
browserSync = require('browser-sync'),
phpconnect = require('gulp-connect-php'),
connect = require('gulp-connect'),
modrewrite = require('connect-modrewrite'),
phpconnect.server({base:'dist/',port: 8010}, function (){
connect.server({
port: 8001,
middleware: function() {
return [
modrewrite([
'^/admin/(.*) - [L]',
'^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
])
];
}
})
browserSync({
injectChanges: true,
proxy: '127.0.0.1:8010'
});
})
This works fine and exactly as I need. The following problem occurs from time to time when I launch it:
[error] You tried to start Browsersync twice! To create multiple instances, use browserSync.create().init()
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::8001
In other words, browserSync starts BEFORE gulp-connect and utilises port 8010 which should be used by gulp-connect and gulp-connect fails to start.
I installed npm sleep package and added the following line before launching browserSync:
sleep.sleep(15)
in other words, I added a 15 seconds delay before launching browserSync.
It works but I bet there is a more elegant solution.
Please, advise.

gulp-connect internally wraps connect, which starts a Node http server.
It emits an event once the server starts called listening. https://nodejs.org/api/net.html#net_event_listening
var
browserSync = require('browser-sync'),
phpconnect = require('gulp-connect-php'),
connect = require('gulp-connect'),
modrewrite = require('connect-modrewrite'),
phpconnect.server({base:'dist/',port: 8010}, function (){
var app = connect.server({
port: 8001,
middleware: function() {
return [
modrewrite([
'^/admin/(.*) - [L]',
'^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
])
];
}
})
app.server.on('listening', function () {
browserSync({
injectChanges: true,
proxy: '127.0.0.1:8010'
});
});

Related

peerjs working on loaclhost but not on heroku?

I'm running my node server on 3000 port and peer server on port 3001.In this scenario its working properly.But when deployed over heroku i'm running my server at 3000 and peer server over 443. In this scenario peerjs not wroking. It might be port alloction issue i guess but i'm unable to find the issue.
peer.js
const myPeer = new Peer( {
secure:true,
host: 'my-app-name.herokuapp.com',
port: 443
})
server.js
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
github link to project : link
New to Heroku. Any help will be appreciated!
Add this to your server file:
var ExpressPeerServer = require("peer").ExpressPeerServer;
var options = {
debug: true,
allow_discovery: true,
};
let peerServer = ExpressPeerServer(server, options);
app.use("/peerjs", peerServer);
And call on client side like this:
var peer = new Peer({
host: "yoursite.herokuapp.com",
port: "",
path: "/peerjs",
});
You Have to Host Two Apps on Heroku. First Your Main App and Second Your PeerJS Server. Because You Cannot Host your App On different Port (i.e. https://your-app-name.herokuapp.com:5000). And Then You can Connect Your Main App PeerJS Client With Your PeerJS Server by using this.
const myPeer = new Peer( {
secure:true,
host: 'my-peerjs-server-name.herokuapp.com',
port: 443
})
Happy Coding!
Just use this Heroku Element to deploy your own peer server with zero configuration. Connect to it from your client providing the host attribute as the url of your Heroku app without the https:// part and you may need to also set secure to true.
{
host: "you_app_name.herokuapp.com", // exclude protocol
secure: true
}
add this in server(index,app) file
const { ExpressPeerServer } = require("peer")
const peerServer = ExpressPeerServer(server, {
debug: true
})
app.use("/peerjs", peerServer);
and in client side add this
const myPeer = new Peer(undefined, {
path: "/peerjs",
host: "/",
port: "443",
})
port should same as your server.listen(port)
This will give invalid frame header for socket io but its fine

How to set custom port number on swagger-api?

I created the project using the following command and chose Express framework.
swagger project create api-name
project starts on http://localhost:10010/
But I set my custom port number 10020.
Starting: /home/rajan/Documents/cse-4-1/web-lab/api/BankApi/app.js...
project started here: http://localhost:10010/
project will restart on changes.
to restart at any time, enter `rs`
try this:
curl http://127.0.0.1:10020/hello?name=Scott
My question is why second and last line showing different port number?
My app.js file:
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
//var port = process.env.PORT || 10010;
var port = 10020;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
I also set the port number on yaml file. Then fixed it.

How to serve data for AJAX calls in a Vue.js-CLI project?

I have a Vue.js CLI project working.
It accesses data via AJAX from localhost port 8080 served by Apache.
After I build the project and copy it to a folder served by Apache, it works fine and can access data via AJAX on that server.
However, during development, since the Vue.js CLI website is being served by Node.js which is serving on a different port (8081), I get a cross-site scripting error) and want to avoid cross-site scripting in general.
What is a way that I could emulate the data being provided, e.g. some kind of server script within the Vue.js-CLI project that would serve mock data on port 8081 for the AJAX calls during the development process, and thus avoid all cross-site scripting issues?
Addendum
In my config/index.js file, I added a proxyTable:
dev: {
env: require("./dev.env"),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: "static",
assetsPublicPath: "/",
proxyTable: {
"/api": {
target: "http://localhost/data.php",
changeOrigin: true
}
},
And now I make my AJAX call like this:
axios({
method: 'post',
url: '/api',
data: {
smartTaskIdCode: 'activityReport',
yearMonth: '2017-09',
pathRewrite: {
"^/api": ""
}
}
But now I see in my JavaScript console:
Error: Request failed with status code 404
Addendum 2
Apparent axios has a problem with rerouting, so I tried it with vue-resource but this code is showing an error:
var data = {
smartTaskIdCode: 'pageActivityByMonth',
yearMonth: '2017-09'
}
this.$http.post('/api', data).then(response => {
this.pageStatus = 'displaying';
this.activity = response.data['activity'];
console.log(this.activity);
}, response => {
this.pageStatus = 'displaying';
console.log('there was an error');
});
The webpack template has its own documentation, and it has a chapter about API proxying during development:
http://vuejs-templates.github.io/webpack/proxy.html
If you use that, it means that you will request your data from the node server during development (and the node server will proxy< the request to your real backend), and the real backend directly in production, so you will have to use different hostnames in each environment.
For that, you can define an env variable in /config/dev.env.js & /config.prod.env.js

grunt qunit in conjunction with grunt server

While running grunt server for developing, How can I separately use the grunt qunit task to run the tests.
While trying to pass ["test/**/*.html"] to the all property, but that fails to run and returns (Warning: 0/0 assertions ran (0ms) Use)
It looks like, it doesn't fire off a phantomjs instance and doesn't find these pates.
So I tried the following
grunt.initConfig({
....
qunit: {
all: {
options: {
urls: ['http://localhost:<%= connect.options.port %>/test/tests/foo.html']
}
}
}
....
});
It only works if when manually include all test html pages (like in the example).
The problem is
My Question is, can grunt qUnit work properly even while using grunt server.
And how can i have ["test/**/*.html"] syntax work correctly. I am sure there must be a better way this should work!
Also, how can use grunt.file.expand be utilized to programmatically add matching files to run in the grunt qunit task.
I've done something like this:
grunt.initConfig({
...
'qunit': {
'files': ['test/**/*.html']
}
...
});
...
// Wrap the qunit task
grunt.renameTask('qunit', 'contrib-qunit');
grunt.registerTask('qunit', function(host, protocol) {
host = host || 'localhost';
protocol = protocol || 'http';
// Turn qunit.files into urls for conrib-qunit
var urls = grunt.util._.map(grunt.file.expand(grunt.config.get('qunit.files')), function(file) {
return protocol + '://' + host + '/' + file;
});
var config = { 'options': { 'urls' : urls } };
grunt.config.set('contrib-qunit.all', config);
grunt.task.run('contrib-qunit');
});

Socket Hang Up when using https.request in node.js

When using https.request with node.js v04.7, I get the following error:
Error: socket hang up
at CleartextStream.<anonymous> (http.js:1272:45)
at CleartextStream.emit (events.js:61:17)
at Array.<anonymous> (tls.js:617:22)
at EventEmitter._tickCallback (node.js:126:26)
Simplified code that will generate the error:
var https = require('https')
, fs = require('fs')
var options = {
host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}
// Set up server and start listening
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
// Wait a second to let the server start up
setTimeout(function() {
var clientRequest = https.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
}, 1000)
I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.
Any ideas on what could be the cause?
In
https.createServer(function (req, res) {
you are missing options when you create the server, should be:
https.createServer(options, function (req, res) {
with your key and cert inside
I had a very similar problem where the response's end event never fired.
Adding this line fixed the problem:
// Hack to emit end on close because of a core bug that never fires end
response.on('close', function () {response.emit('end')});
I found an example of this in the request library mentioned in the previous answer.
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.
In the request 1.2.0 source code, main.js line 76, I see
http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');
Looking at the http.js source code, I see
exports.createClient = function(port, host) {
var c = new Client();
c.port = port;
c.host = host;
return c;
};
It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.
Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').
It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.
I had a similar problem and i think i got a fix. but then I have another socket problem.
See my solution here: http://groups.google.com/group/nodejs/browse_thread/thread/9189df2597aa199e/b83b16c08a051706?lnk=gst&q=hang+up#b83b16c08a051706
key point: use 0.4.8, http.request instead of http.createClient.
However, the new problem is, if I let the program running for long time, (I actually left the program running but no activity during weekend), then I will get socket hang up error when I send a request to http Server. (not even reach the http.request). I don't know if it is because of my code, or it is different problem with http Server