How to use gulp-connect with IIS - iis

I'm using the library gulp-connect to refresh my browser when I change something in my frontend... but like you know it works in a server like localhost:8080... the problems is that my backend is in IIS.I wonder if is there some way to connect my IIS with gulp-connet to refresh my code when I change it in localhost:80 (IIS) ? Maybe a middleware or something like that?

You would be better off using browsersync:
//Set up the proxy
const browserSyncStart = () => { browserSync.init({ proxy: 'localhost' }); };
//set up a watch
const watcher = () => { return gulp.watch(src).on('all', () => { compileLess().on('end', publish); }); };
//Let the publish function also reload the browser
export const publish = () => {
// Check if the folder exists
if (fs.existsSync(config.publishPath)) {
//copy from /dist to /wwwroot
del(config.publishPath + 'dist/**/*', { force: true });
gulp.src(config.theming.dist + '/**/*').pipe(gulp.dest(config.publishPath + 'dist'));
browserSync.reload();
} else {
log(c.red(config.publishPath + ' does not exist.'));
}
};
//Create a task, run with gulp watch
export const watch = gulp.parallel(browserSyncStart, watcher);

Related

404 on dynamic paths after deploy in Next.JS

I fetch data in my Next JS app from Sanity to create dynamic routes.
Like this:
export const getStaticPaths = async () => {
const res = await client.fetch(`*[_type in ["work"] ]`);
const data = await res;
const paths = data.map((e) => {
return {
params: { slug: e.slug.current },
};
});
return {
paths,
fallback: false,
};
};
export const getStaticProps = async (context) => {
const slug = context.params.slug;
const res = await client.fetch(`*[_type == "work" && slug.current == "${slug}"]
`);
const data = await res;
const resAll = await client.fetch(`*[_type == "work"] | order(order asc)`);
const dataAll = await resAll;
return {
props: {
post: data[0],
dataAll,
},
revalidate: 1, // 10 seconds
};
};
on localhost everything works fine and quick, on Netlify i am getting a 404 error for every newly generated route.
only after a redeploy the page shows up.
My directory looks like this:
-works
----[slug].jsx
----index.jsx
Why doesnt netlify recognize the new path right away?
Also, every change to existing content on the site via sanity takes rather long to show up on netlify.
I tried creating a build hook in netlify and listen to the changes in content, to trigger a build on the server every time new content is added.
This seems like a hacky workaround, though. There must be a simpler way to get this to work.
Possible Solution:
I change fallback from false to true, and it works on Netlify without getting a 404.
It breaks on localhost though, but works on the live server.

Including MQTT in electron application blocks `.openDevTools`

I have quite strange problem.
I'm developing electron application.
Lets focus only on main.js - it has all the basic components and then I have setupMQTT() function which handles all the MQTT stuff. So my main.js looks something like this. For the sake of simplicity I will omit a few things.
const { app, BrowserWindow } = require("electron");
const path = require("path");
const url = require("url");
import { connect, MqttClient } from "mqtt" // << this is for MQTT
// .. omitting
let MQTT: MqttClient;
function createWindow() {
let win = new BrowserWindow(/* ..omitting.. */);
win.loadURL(/* ..omitting.. */);
win.webContents.openDevTools({ mode: 'detach' });
win.on("closed", () => {
win = null;
});
}
// .. omitting
app.on("ready", () => {
createWindow();
setupMQTT(); // << if I comment this out `....openDevTools` works
});
function setupMQTT() {
MQTT = connect('...', {
hostname: '...',
port: 8883,
protocol: 'mqtts'
});
MQTT.on('connect', () => {});
MQTT.on('message', (topic, value) => {});
MQTT.on('error', (error) => {});
}
So if I comment out setupMQTT() dev tools will show, otherwise dev tools will not (also invoking them from menu doesn't work)
note - MQTT works (I get messages and all)
Any ideas? Thanks!

Electron - ECONNREFUSED on all outgoing (xhr) requests in the web app - but the server's up and CORS is enabled.

I'm wrapping a web application inside an Electron app. The web application tries to connect to a remote server - which is publicly accessible and CORS is enabled. I can access the server fine using the browser, and running the web app in a browser also works. However, after wrapping it in the Electron app, it all fails.
The electron app runs a local webserver (express), which hosts the files. The files are then loaded into the BrowserWindow. Code's below. In the screenshot, you can see the type of error I'm getting. The server is accessible at http://demo.signalk.org
Any ideas? The webapp uses superagent to make the actual request.
An image of the error
The code:
const electron = require('electron')
const express = require('express')
const join = require('path').join
const url = require('url')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let server = null
let mainScreen = null
let mainWindow = null
app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
function initServer() {
if (server !== null) {
return
}
const path = join(__dirname, '../www')
console.log('static path', path)
server = express()
server.use('/', express.static(path))
server.listen(33013, '127.0.0.1')
}
function createWindow() {
if (mainWindow !== null) {
return
}
initServer()
mainScreen = electron.screen.getPrimaryDisplay()
mainWindow = new BrowserWindow({
height: mainScreen.workAreaSize.height,
width: 450,
show: false,
icon: join(__dirname, '../../resources/Icon.png'),
})
mainWindow.loadURL('http://127.0.0.1:33013')
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show()
})
mainWindow.on('closed', () => {
mainWindow = null
mainScreen = null
server = null
})
}
app.on('ready', () => {
createWindow()
})
app.on('window-all-closed', () => {
if (process.platform === 'darwin') {
return
}
app.quit()
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
module.exports = {
app,
mainWindow,
}
I figured it out... documenting for archive/google purposes.
What I did. I added some flags to enable remote debugging:
app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
As you can probably guess, I copied that from somewhere without thinking. Those host rules (really obvious, when you think about it) map every hostname to 127.0.0.1.

Execute a middleware one-time only at server startup in Koa v2

I created this middleware which executing only once when any route in the website gets the first hit from a visitor:
// pg-promise
const db = require('./db/pgp').db;
const pgp = require('./db/pgp').pgp;
app.use(async (ctx, next) => {
try {
ctx.db = db;
ctx.pgp = pgp;
} catch (err) {
debugErr(`PGP ERROR: ${err.message}` || err);
}
await next();
});
// One-Time middleware
// https://github.com/expressjs/express/issues/2457
const oneTime = (fn) => {
try {
let done = false;
const res = (ctx, next) => {
if (done === false) {
fn(ctx, next);
done = true;
}
next();
};
return res;
} catch (err) {
debugErr(`oneTime ERROR: ${err.message}` || err);
}
};
const oneTimeQuery = async (ctx) => {
const result = await ctx.db.proc('version', [], a => a.version);
debugLog(result);
};
app.use(oneTime(oneTimeQuery));
This code executing on the first-time only when a user visiting the website, resulting:
app:log Listening on port 3000 +13ms
app:req GET / 200 - 24ms +2s
23:07:15 connect(postgres#postgres)
23:07:15 SELECT * FROM version()
23:07:15 disconnect(postgres#postgres)
app:log PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit +125ms
My problem is that I want to execute it at the server start, when there's no any visit on the site.
The future purpose of this code will be to check the existence of tables in the database.
Solution:
Placing this in ./bin/www before the const server = http.createServer(app.callback()); declaration helped:
const query = async () => {
const db = require('../db/pgp').db;
const pgp = require('../db/pgp').pgp;
const result = await db.proc('version', [], a => a.version);
debugLog(`www: ${result}`);
pgp.end(); // for immediate app exit, closing the connection pool (synchronous)
};
query();
You could start your application using a js script that requires your app and uses node's native http module to fire up the server. Exactly like in koa-generator (click).
This is in your app.js file:
const app = require('koa')();
...
module.exports = app;
And then this is in your script to fire up the server:
const app = require('./app');
const http = require('http');
[this is the place where you should run your code before server starts]
const server = http.createServer(app.callback());
server.listen(port);
Afterwards you start your application with:
node [script_name].js
Of course keep in mind the async nature of node when doing it this way. What I mean by that - run the 'listen' method on 'server' variable in callback/promise.

Koajs and Socket.io integration

Please, need help with integration of sockets with this koajs skeleton
Here is the code from server side file (/src/index.js)
'use strict';
// 3rd party
require('dotenv').config(); // Load env vars from .env, always run this early
const koa = require('koa');
const bouncer = require('koa-bouncer');
const nunjucksRender = require('koa-nunjucks-render');
const debug = require('debug')('app:index');
// 1st party
const config = require('./config');
const mw = require('./middleware');
const belt = require('./belt');
const cancan = require('./cancan');
////////////////////////////////////////////////////////////
const app = koa();
app.poweredBy = false;
app.proxy = config.TRUST_PROXY;
////////////////////////////////////////////////////////////
// Configure view-layer (nunjucks)
//
// We can override options send directly to nunjucks.
// https://mozilla.github.io/nunjucks/api.html#configure
////////////////////////////////////////////////////////////
const nunjucksOptions = {
// `yield this.render('show_user')` will assume that a show_user.html exists
ext: '.html',
noCache: config.NODE_ENV === 'development',
// don't throw template errors in development if we try to render
// a null/undefined like {{ x }}. in theory, setting it to true prevents
// bugs and forces you to be explicit about {{ x or '' }}, but in reality,
// often more annoying than it's worth.
throwOnUndefined: false,
// globals are bindings we want to expose to all templates
globals: {
// let us use `can(USER, ACTION, TARGET)` authorization-checks in templates
can: cancan.can,
},
// filters are functions that we can pipe values to from nunjucks templates.
// e.g. {{ user.uname | md5 | toAvatarUrl }}
filters: {
json: x => JSON.stringify(x, null, ' '),
formatDate: belt.formatDate,
nl2br: belt.nl2br,
md5: belt.md5,
toAvatarUrl: belt.toAvatarUrl,
autolink: belt.autolink,
},
};
////////////////////////////////////////////////////////////
// Middleware
////////////////////////////////////////////////////////////
app.use(mw.ensureReferer());
app.use(require('koa-helmet')());
app.use(require('koa-compress')());
app.use(require('koa-static')('public'));
// Don't show logger in test mode
if (config.NODE_ENV !== 'test') {
app.use(require('koa-logger')());
}
app.use(require('koa-body')({ multipart: true }));
app.use(mw.methodOverride()); // Must come after body parser
app.use(mw.removeTrailingSlash());
app.use(mw.wrapCurrUser());
app.use(mw.wrapFlash('flash'));
app.use(bouncer.middleware());
app.use(mw.handleBouncerValidationError()); // Must come after bouncer.middleware()
app.use(nunjucksRender('views', nunjucksOptions));
// Provide a convience function for protecting our routes behind
// our authorization rules. If authorization check fails, 404 response.
//
// Usage:
//
// router.get('/topics/:id', function*() {
// const topic = yield db.getTopicById(this.params.id);
// this.assertAuthorized(this.currUser, 'READ_TOPIC', topic);
// ...
// });
app.use(function*(next) {
this.assertAuthorized = (user, action, target) => {
const isAuthorized = cancan.can(user, action, target);
const uname = (user && user.uname) || '<Guest>';
debug('[assertAuthorized] Can %s %s: %s', uname, action, isAuthorized);
this.assert(isAuthorized, 404);
};
yield* next;
});
////////////////////////////////////////////////////////////
// Routes
////////////////////////////////////////////////////////////
app.use(require('./routes').routes());
app.use(require('./routes/authentication').routes());
app.use(require('./routes/admin').routes());
////////////////////////////////////////////////////////////
// If we run this file directly (npm start, npm run start-dev, node src/index.js)
// then start the server. Else, if we require() this file (like from
// our tests), then don't start the server and instead just export the app.
if (require.main === module) {
app.listen(config.PORT, function() {
console.log('Listening on port', config.PORT);
});
} else {
module.exports = app;
}
On client side (/views/master.js) :
....
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
socket.on('news', function (data) {
console.log('received news with data: ');
console.log(data);
});
function myclick () {
console.log("click");
socket.emit('click', { clickdata: 'someone clicked on the button' });
}
</script>
<button type="button" onclick="myclick();">Click Me and watch console at server and in browser.</button>
....
Please, can someone explain to me hot to integrate socket.io with koas server? I've installed ["socket.io": "^1.4.5"]. What are the next steps?
PS: Sory about my ugly english.
I've founded a solution here. Bellow is a general code sample
const Koa = require( 'koa' )
const IO = require( 'koa-socket' )
const app = new Koa()
const io = new IO()
app.use( ... )
io.attach( app )
io.on( 'join', ( ctx, data ) => {
console.log( 'join event fired', data )
})
app.listen( process.env.PORT || 3000 )

Resources