diff --git a/lib/http-protocol.js b/lib/http-protocol.js index 6bd2c4daf..43dbd7db6 100644 --- a/lib/http-protocol.js +++ b/lib/http-protocol.js @@ -3,6 +3,14 @@ var queryString = require("qs"); var proto = exports; var instanceMethods = ["exit", "notify", "pause", "resume"]; +var getBody = require('raw-body'); +const permittedSocketEvents = [ + "file:reload", + "browser:reload", + "browser:notify", + "browser:location", + "options:set" +]; /** * Does the requested method expect an instance of BrowserSync @@ -42,6 +50,32 @@ proto.getUrl = function(args, url) { */ proto.middleware = function(bs) { return function(req, res) { + if (req.method === 'POST') { + return getBody(req, function(err, body) { + if (err) { + const output = [ + "Error: could not parse JSON.", + ]; + res.writeHead(500, { "Content-Type": "text/plain" }); + return res.end(output.join("\n")); + } + try { + const [name, payload] = JSON.parse(body.toString()); + if (permittedSocketEvents.indexOf(name) > -1) { + bs.io.sockets.emit(name, payload); + return res.end(`Browsersync HTTP Protocol received: ${name} ${JSON.stringify(payload)}`); + } else { + return res.end(`Browsersync HTTP Protocol name not supported: ${name}`); + } + } catch (e) { + const output = [ + `Error: ${e.message}`, + ]; + res.writeHead(500, { "Content-Type": "text/plain" }); + return res.end(output.join("\n")); + } + }); + } var params = queryString.parse(req.url.replace(/^.*\?/, "")); var output; diff --git a/package.json b/package.json index 62d89bd7a..cb0cbc1c4 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "opn": "4.0.2", "portscanner": "2.1.1", "qs": "6.2.1", + "raw-body": "^2.3.2", "resp-modifier": "6.0.2", "rx": "4.1.0", "serve-index": "1.8.0",