Skip to content

Commit

Permalink
feat: (http-protocol) support POST requests over HTTP Protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
shakyShane committed Apr 29, 2018
1 parent 31bace2 commit e4754c9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/http-protocol.js
Expand Up @@ -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
Expand Down Expand Up @@ -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;

Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -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",
Expand Down

0 comments on commit e4754c9

Please sign in to comment.