N
N
Nikita Kit2018-06-08 13:41:13
Node.js
Nikita Kit, 2018-06-08 13:41:13

How to respond with an index to all get-requests to browserSync?

Hello.
Need help with middleware handling in browserSync. I have a one-pager, everything is fine when navigating through the routes, but if I change the code on some route, the reload of the tab is called and a request is made to a non-existent page, to which broserSync answers cannot get.
The redirect disappears, of course. It is necessary to respond to any get with an index html, but res.send and res.sendFile in middleWare browserSync are not defined. There is exactly one example in the plugin docs about middleware. logil res - did not give anything obvious.

UPD. native node is a terribly inconvenient thing. I decided to use native modules, but I can't figure out how to pass data to response anyway.

if (req.headers["accept"] && req.headers["accept"].includes('text/html')){
              fs.readFile(path.join(taskTarget, 'index.html'), function(err, data){
                if (err) throw err;
                res.end(data);
              })
            }
            next()

Sobsn I decided to check all content types to html and give index markup. It turned out to intercept the request and pull data from index. No way to give. Now this code works as well as without it, even though the condition is executed. res.end(data) doesn't work. Tried res.write(data);res.end(); - the node complains about write after end, although, obviously, write is called before end....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergiu Mitu, 2018-06-08
@ShadowOfCasper

i use this middleware

const browserSyncConfig = {
  server: {
    baseDir: "./dev/client",
    middleware: [
      function (req, res, next) { // Allow CORS
        res.setHeader('Access-Control-Allow-Origin', '*');
        next();
      },
      historyApiFallback() //for SPA application
    ]
  },
  host: 'localhost',
  port: 3000,
  notify: false,
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question