Hi, that is a cool feature!
It's not something we'd put into the core though - but you could easily add a middleware, or roll your own solution, something like this perhaps?
var mocks = {
"/mock": function (req, res) {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({
name: "shane"
}));
}
}
browserSync({
server: {
baseDir: "test/fixtures",
middleware: function (req, res, next) {
if (mocks[req.url]) {
mocks[req.url](req, res);
}
next();
}
}
});
You could make it fancier of course, but that example should show you how you can add functionality to BrowserSync (also, we use Connect under the hood, so any of their middlewares will work too)
Hope that helps :)
Thanks for quickly replying!
According to https://github.com/leeluolee/puer#use-as-connectexpress-middleware, it seems I can also use puer as such middleware, right? I'm not really sure how to configure it as BrowserSync's middleware, could you give me some hint?
Thanks.
But that's for all the features of peur, it's probably not what you want
What you really want is express's router (that's how puer is doing it).
but when serve-index is enabled, POST requests are ignored.
Here: https://github.com/expressjs/serve-index/blob/267913151b334ba1fa6cc273c202b7eda55fa2f1/index.js#L93
browserSync({
server: {
directory: true, // serve-index gets enabled by setting directory: true.
baseDir: "test/fixtures",
middleware: function (req, res, next) {
if (mocks[req.url]) {
mocks[req.url](req, res);
}
next();
}
}
});
closing as this should be done via middleware - we are also going to add this type of functionality to UI in the future. but it doesn't belong in core.
@blvz - to overcome that issue, use the api
require("browser-sync")({
open: false,
server: {
baseDir: "src",
directory: true
}
}, function (err, bs) {
bs.addMiddleware('', function (req, res, next) {
if (mocks[req.url]) {
return mocks[req.url](req, res);
}
next();
}, {override: true});
});
{override: true} will push middlewares to the front of the stack and providing you don't call next(), everything will work - even with POST
@shakyShane good to know. thank you.
@shakyShane I'm trying to make something like this work on an assemble project (using Grunt). Is it possible to use the bs api the way you demonstrated from within grunt options? or how would I need to approach that?
And will this work with outgoing requests?
Just to update, browsersync now has this option:
// Per-route middleware
// NOTE: requires v2.12.1
middleware: [
{
route: "/api",
handle: function (req, res, next) {
// handle any requests at /api
}
}
]
Most helpful comment
Just to update, browsersync now has this option:
https://www.browsersync.io/docs/options