I'm working on a video chat application using EasyRTC and Xirsys. It works fine on its own (using the Google STUN server), but fails when I create a listener for the getIceConfig event. The EasyRTC server is on port 8080, and I also have an Apache server running on port 80. I've set up my server.js file as follows:
// Load required modules
var http = require("http"); // http server core module
var express = require("express"); // web framework external module
var io = require("socket.io"); // web socket external module
var easyrtc = require("../"); // EasyRTC external module
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var httpApp = express();
httpApp.use(express.static(__dirname + "/static/"));
// Start Express http server on port 8080
var webServer = http.createServer(httpApp).listen(8080);
// Start Socket.io so it attaches itself to Express server
var socketServer = io.listen(webServer, {"log level":1});
easyrtc.setOption("logLevel", "debug");
// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj){
if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) {
callback(err, connectionObj);
return;
}
connectionObj.setField("credential", msg.msgData.credential, {"isShared":false});
console.log("["+easyrtcid+"] Credential saved!", connectionObj.getFieldValueSync("credential"));
callback(err, connectionObj);
});
});
// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
console.log("["+connectionObj.getEasyrtcid()+"] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});
// Start EasyRTC server
var rtc = easyrtc.listen(httpApp, socketServer, null, function(err, rtcRef) {
console.log("Initiated");
rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
console.log("roomCreate fired! Trying to create: " + roomName);
appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
});
});
easyrtc.on("getIceConfig", function(connectionObj, callback) {
// This object will take in an array of XirSys STUN and TURN servers
var iceConfig = [];
request({
url: 'https://service.xirsys.com/ice',
qs: {
ident: "***",
secret: "***",
domain: "***",
application: "default",
room: "default",
secure: 1
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// body.d.iceServers is where the array of ICE servers lives
iceConfig = body.d.iceServers;
console.log(iceConfig);
callback(null, iceConfig);
}
}
});
});
The debugging error messages are below:
info - EasyRTC: Starting EasyRTC Server (v1.0.15) on Node (v4.4.5)
debug - EasyRTC: Emitting event 'startup'
debug - EasyRTC: Running func 'onStartup'
debug - EasyRTC: Configuring Http server
debug - EasyRTC: Setting up demos to be accessed from '/demos/'
debug - EasyRTC: Setting up API files to be accessed from '/easyrtc/'
debug - EasyRTC: Configuring Socket server
debug - EasyRTC: Creating application: 'default'
debug - EasyRTC: [default] Room [default] Running func 'onRoomCreate'
debug - EasyRTC: Creating room: 'default' with options: {}
info - EasyRTC: EasyRTC Server Ready For Connections (v1.0.15)
Initiated
debug - EasyRTC: [U0LMzF8jbIBdxq3sGtxP] Socket connected
debug - EasyRTC: Emitting event 'connection'
debug - EasyRTC: Running func 'onConnection'
debug - EasyRTC: [U0LMzF8jbIBdxq3sGtxP] Running func 'onEasyrtcAuth'
debug - EasyRTC: Attempt to request non-existent application name: 'easyrtc.audioVideoSimple'
debug - EasyRTC: Emitting Authenticate
debug - EasyRTC: Creating application: 'easyrtc.audioVideoSimple'
roomCreate fired! Trying to create: default
debug - EasyRTC: [easyrtc.audioVideoSimple] Room [default] Running func 'onRoomCreate'
debug - EasyRTC: Creating room: 'default' with options: {}
[U0LMzF8jbIBdxq3sGtxP] Credential retrieved! null
debug - EasyRTC: [easyrtc.audioVideoSimple][U0LMzF8jbIBdxq3sGtxP] Running func 'onRoomJoin'
debug - EasyRTC: [easyrtc.audioVideoSimple][U0LMzF8jbIBdxq3sGtxP] Room [default] Running func 'connectionRoomObj.emitRoomDataDelta'
debug - EasyRTC: [easyrtc.audioVideoSimple][U0LMzF8jbIBdxq3sGtxP] Room [default] Running func 'connectionRoomObj.generateRoomDataDelta'
debug - EasyRTC: [easyrtc.audioVideoSimple][U0LMzF8jbIBdxq3sGtxP] Running func 'onSendToken'
C:\Users\Jamie\nodes\easyrtc\node_modules\easyrtc\server_example\server.js:58
request({
^
ReferenceError: request is not defined
at EventEmitter.<anonymous> (C:\Users\Jamie\nodes\easyrtc\node_modules\easyrtc\server_example\server.js:58:5)
at emitTwo (events.js:87:13)
at EventEmitter.emit (events.js:172:7)
at C:\Users\Jamie\nodes\easyrtc\node_modules\easyrtc\lib\easyrtc_default_event_listeners.js:1057:34
at fn (C:\Users\Jamie\nodes\easyrtc\node_modules\easyrtc\node_modules\async\lib\async.js:582:34)
at Immediate._onImmediate (C:\Users\Jamie\nodes\easyrtc\node_modules\easyrtc\node_modules\async\lib\async.js:498:34)
at processImmediate [as _immediateCallback] (timers.js:383:17)
info - EasyRTC: Starting EasyRTC Server (v1.0.15) on Node (v4.4.5)
debug - EasyRTC: Emitting event 'startup'
debug - EasyRTC: Running func 'onStartup'
debug - EasyRTC: Configuring Http server
debug - EasyRTC: Setting up demos to be accessed from '/demos/'
debug - EasyRTC: Setting up API files to be accessed from '/easyrtc/'
debug - EasyRTC: Configuring Socket server
debug - EasyRTC: Creating application: 'default'
debug - EasyRTC: [default] Room [default] Running func 'onRoomCreate'
debug - EasyRTC: Creating room: 'default' with options: {}
info - EasyRTC: EasyRTC Server Ready For Connections (v1.0.15)
Initiated
debug - EasyRTC: [YBCNOMSW7zbRXF0IH_g2] Socket connected
debug - EasyRTC: Emitting event 'connection'
debug - EasyRTC: Running func 'onConnection'
debug - EasyRTC: [YBCNOMSW7zbRXF0IH_g2] Running func 'onEasyrtcAuth'
debug - EasyRTC: Attempt to request non-existent application name: 'easyrtc.audioVideoSimple'
debug - EasyRTC: Emitting Authenticate
debug - EasyRTC: Creating application: 'easyrtc.audioVideoSimple'
roomCreate fired! Trying to create: default
debug - EasyRTC: [easyrtc.audioVideoSimple] Room [default] Running func 'onRoomCreate'
debug - EasyRTC: Creating room: 'default' with options: {}
[YBCNOMSW7zbRXF0IH_g2] Credential retrieved! null
debug - EasyRTC: [easyrtc.audioVideoSimple][YBCNOMSW7zbRXF0IH_g2] Running func 'onRoomJoin'
debug - EasyRTC: [easyrtc.audioVideoSimple][YBCNOMSW7zbRXF0IH_g2] Room [default] Running func 'connectionRoomObj.emitRoomDataDelta'
debug - EasyRTC: [easyrtc.audioVideoSimple][YBCNOMSW7zbRXF0IH_g2] Room [default] Running func 'connectionRoomObj.generateRoomDataDelta'
debug - EasyRTC: [easyrtc.audioVideoSimple][YBCNOMSW7zbRXF0IH_g2] Running func 'onSendToken'
[...path]\node_modules\easyrtc\server_example\server.js:58
request({
^
ReferenceError: request is not defined
at EventEmitter.<anonymous> ([...path]\node_modules\easyrtc\server_example\server.js:58:5)
at emitTwo (events.js:87:13)
at EventEmitter.emit (events.js:172:7)
at [...path]\node_modules\easyrtc\lib\easyrtc_default_event_listeners.js:1057:34
at fn (C[...path]\node_modules\easyrtc\node_modules\async\lib\async.js:582:34)
at Immediate._onImmediate ([...path]\node_modules\easyrtc\node_modules\async\lib\async.js:498:34)
at processImmediate [as _immediateCallback] (timers.js:383:17)
Any ideas about what is causing this? It happens in both chrome and firefox. Thanks.
Here's your error:
ReferenceError: request is not defined
You forgot to invoke request with the http object.
Here's your fix:
Change this:
request({
url: 'https://service.xirsys.com/ice',
...
To be this:
http.request({
url: 'https://service.xirsys.com/ice',
...
Related
I am trying to put a value in Infinispan cache using Hotrod nodeJS client. The code runs fine if the server is installed locally. However, when I run the same code with Infinispan server hosted on docker container I get the following error
java.lang.SecurityException: ISPN006017: Unauthorized 'PUT' operation
try {
client = await infinispan.client({
port: 11222,
host: '127.0.0.1'
}, {
cacheName: 'testcache'
});
console.log(`Connected to cache`);
await client.put('test', 'hello 1');
await client.disconnect();
} catch (e) {
console.log(e);
await client.disconnect();
}
I have tried setting CORS Allow all option on the server as well
Need to provide custom config.yaml to docker with following configurations
endpoints:
hotrod:
auth: false
enabled: false
qop: auth
serverName: infinispan
Unfortunately the nodejs client doesn't support authentication yet. The issue to implement this is https://issues.redhat.com/projects/HRJS/issues/HRJS-36
The error code is code ETIMEOUT. I am using SQL Server 2014, NodeJs version v12.16.2 and I am running this code in Visual Studio Code.
I have created the database and the table is also created with some records. For the server name, I have also tried giving the FQDN, but it didn't work.
This is the code snippet:
const express = require('express');
const app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
app.get('/', function(req, res) {
res.send('<hHii</h');
});
const sql = require('mssql');
var config = {
user: 'domain\username',
password: 'mypwd',
server: 'servername',
host: 'hostname',
port: '1433',
driver: 'tedious',
database: 'DBname',
options: {
instanceName: 'instancename'
}
};
sql.connect(config, function(err) {
if (err)
console.log(err);
let sqlRequest = new sql.Request();
//var sqlRequest = new sql.Request(connection)
let sqlQuery = 'SELECT * from TestTable';
sqlRequest.query(sqlQuery, function(err, data) {
if (err) console.log(err);
console.log(data);
//console.table(data.recordset);
// console.log(data.rowAffected);
//console.log(data.recordset[0]);
sql.close()
});
});
const webserver = app.listen(5000, function() {
console.log('server is up and running....');
});
Error:
tedious deprecated The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or`false` explicitly to silence this message.
node_modules\mssql\lib\tedious\connection-pool.js:61:23
server is up and running....
ConnectionError: Failed to connect to servername\instantname in 15000ms
at Connection.<anonymous(..\SQL\Sample\sample\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:417:26)
at Connection.emit (events.js:310:20)
at Connection.connectTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1195:10)
at Timeout._onTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1157:12)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ETIMEOUT',
originalError: ConnectionError: Failed to connect to INPUNPSURWADE\DA in 15000ms
at ConnectionError (..\SQL\Sample\sample\node_modules\tedious\lib\errors.js:13:12)
at Connection.connectTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1195:54)
at Timeout._onTimeout (..\SQL\Sample\sample\node_modules\tedious\lib\connection.js:1157:12)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
message: 'Failed to connect to servername\instantname in 15000ms',
code: 'ETIMEOUT'
},
name: 'ConnectionError'
}
ConnectionError: Connection is closed.
at Request._query (..\SQL\Sample\sample\node_modules\mssql\lib\base\request.js:462:37)
at Request._query (..\SQL\Sample\sample\node_modules\mssql\lib\tedious\request.js:346:11)
at Request.query (..\SQL\Sample\sample\node_modules\mssql\lib\base\request.js:398:12)
at Immediate.<anonymous(..\SQL\Sample\sample\index.js:43:12)
at processImmediate (internal/timers.js:458:21) {
code: 'ECONNCLOSED',
name: 'ConnectionError'
}
Go to Start menu in Windows, search for "Services" and open it.
Look for "SQL Server Browser"
Right click on it and go to Properties.
Switch "Start up type" to "Automatic"
Click Ok
Right click on it again and Start the service.
It should work after that!
You might make a typo in host/port, or the server doesn't listen external interfaces (it might be configured to liten 127.0.0.1 only)
to check that the server is listening to incoming connections, run in terminal the following:
telnet <hostname> <port>
(mac/linux only)
If it says "Unable to connect to remote host: Connection refused" it means the host is there but it doesn't listen the port.
If it says "Unable to connect to remote host: Connection timed out" then the host might not be there, ot doesn't listen to the port.
You may also want to check if your firewall allows connection to that server.
I'm trying SignalR on ASP.NET Core. It works fine running from VisaulStudio debugger.
However it does not work in deployed code, showing the error message "WebSocket is not in the OPEN state" and "Handshake was canceled". What is the possible cause of the problem?
Microsoft.AspNetCore.Mvc 2.2.0
Microsoft.AspNetCore.SignalR 1.1.0
#aspnet/signalr 1.1.2
Bootstrap4
jQuery v3.1.0
Kestrel
No HTTPS SSL
Tried with Windows 7 and Ubuntu 18.4
Network Console on Google Chrome
WebSocket is not in the OPEN state (kms-event-exit.js:12)
Uncaught Error: Seerver returned handshake error: Handshake was canceled. (signalr.min.js:16)
at HubConnection.processHandshakeResponse (signalr.min.js:16)
at HubConnection.processIncomingData (signalr.min.js:16)
at WebSocketTransport.HubConnection.connection.onreceive (signalr.min.js:16)
at WebSocket.webSocket.onmessag (signalr.min.js:16)
[2019-04-06T01:06:41.965Z] Error: Connection disconnected with error 'Error: Server returned handshake error: Handshake was canceled.'. signalr.min.js:16
Uncaught (in promise) Server returned handshake error: Handshake was canceled. (signalr.min.js:16)
Startup functions.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorOptions(options => options.AllowRecompilingViewsOnFileChange = true);
services.AddSignalR(options => options.EnableDetailedErrors = true);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
if (!env.IsDevelopment())
{
//app.UseExceptionHandler("/Home/Main");
app.UseHsts();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<Hubs.KmsHub>("/KmsHub");
routes.MapHub<Hubs.AllResetHub>("/AllResetHub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaDefault",
template: "{area:exists}/{controller=Home}/{action=Main}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Main}/{id?}/{exit?}");
});
}
Logs
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[4]
Establishing new connection.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[5]
OnConnectedAsync started.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[1]
Socket opened using Sub-Protocol: '(null)'.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/favicon.ico'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\favicon.ico'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 6.664ms 200 image/x-icon
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/lib/Popper/popper.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 3.4573ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/lib/bootstrap/dist/js/bootstrap.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/lib/signalr/dist/browser/signalr.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 2.3443ms 404
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.min.js.map'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\lib\boo
tstrap\dist\js\bootstrap.min.js.map'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 114.858ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/lib/bootstrap/dist/css/bootstrap.min.css.map
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css.map'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\lib\b
ootstrap\dist\css\bootstrap.min.css.map'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 18.0356ms 200 text/plain
dbug: Microsoft.AspNetCore.SignalR.HubConnectionContext[2]
Handshake was canceled.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[7]
Waiting for the client to close the socket.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[2]
Socket closed.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionManager[2]
Removing connection 8K2CDgDs6jWXM7DPMWk_Dg from the list of connections.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 15047.5227ms 101
JavaScript code which caught the exception.
function kmsEventExit(url) {
var exitButton = document.getElementById("exitButton");
var connection = new signalR.HubConnectionBuilder().withUrl(url + "/KmsHub").build();
//Disable send button until connection is established
exitButton.disabled = true;
//Wait until connection finishes.
connection.start().then(function () {
exitButton.disabled = false;
}).catch(function (err) {
return console.error(err.toString()); //WebSocket is not in the OPEN state
});
//Call ExitKms on clicking the button.
exitButton.addEventListener("click", function (event) {
connection.invoke("ExitKms").catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
//Catch the result.
connection.on("ExitKmsResult", function (isAlert, options) {
if (isAlert) {
swal(JSON.parse(options));
}
});
}
There has been an workaround posted in a GitHub Issue that has worked for me.
Before connecting, add:
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
Using this method, there's no need to remove pace.js.
Important note: if you are using Blazor Server, you will face the same issue. Remove pace.js then, as it's quite useless in this case.
I have identified the problem!
It did not work because pace.js was not compatible with signalr.js. WebSocket variable was duplicated in these two plugins. SignalR works fine after removing pace.js.
SignalR on VisualStudio worked with pace.js because it uses SSE and IIS Express, instead of WebSocket and Kestrel, thus pace.js and signalr.js can be compatible with this particular configuration.
Reference:
https://github.com/aspnet/SignalR/issues/2389
As Identified above, pace and signalr are not directly compatible, however putting the script below before loading pace.js will resolve the problem instead of outrightly remove pace.js
<script>
window.paceOptions = { ajax: { ignoreURLs: ['mainHub', '__browserLink', 'browserLinkSignalR'], trackWebSockets: false } }
</script>
Reference to above answer: https://stackoverflow.com/questions/54770354/how-to-use-asp-net-core-signalr-with-pace-js
The value of 'mainHub' is the signalR hub in your C# application you are connecting to.
I am able to work with Truffle and Ganache-cli. Have deployed the contract and can play with that using truffle console
truffle(development)>
Voting.deployed().then(function(contractInstance)
{contractInstance.voteForCandidate('Rama').then(function(v)
{console.log(v)})})
undefined
truffle(development)> { tx:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
receipt:
{ transactionHash:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
transactionIndex: 0,
blockHash:
'0x639482c03dba071973c162668903ab98fb6ba4dbd8878e15ec7539b83f0e888f',
blockNumber: 10,
gasUsed: 28387,
cumulativeGasUsed: 28387,
contractAddress: null,
logs: [],
status: '0x01',
logsBloom: ... }
Now when i started a server using "npm run dev". Server started fine but is not connecting with the Blockchain
i am getting the error
Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)
This is my truffle.js
// Allows us to use ES6 in our migrations and tests.
require('babel-register')
module.exports = {
networks: {
development: {
host: '127.0.0.1',
port: 8545,
network_id: '*', // Match any network id
gas: 1470000
}
}
}
Can you please guide me how i can connect ?
Solve the issue.
issue was at currentProvider, i gave the url of ganache blockchain provider and it worked.
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source like Metamask")
// Use Mist/MetaMask's provider
// window.web3 = new Web3(web3.currentProvider);
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
In your truffle.js, change 8545 to 7545.
Or, in Ganache (GUI), click the gear in the upper right corner and change the port number from 7545 to 8545, then restart. With ganache-cli use -p 8545 option on startup to set 8545 as the port to listen on.
Either way, the mismatch seems to be the issue; these numbers should match. This is a common issue.
Also feel free to check out ethereum.stackexchange.com. If you want your question moved there, you can flag it and leave a message for a moderator to do that.
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'
});
});