Home > Net >  Change url when sending file with Express
Change url when sending file with Express

Time:02-18

I want to send an HTML file as a response but when it does it keeps the current url. I have read about the location method but it does not work for me, I would like something like:

The source url is this: localhost/login

Sending this answer

res.location('/live').sendFile(path.join(__dirname, "../pages/live.html"));

I was trying to get something like this

  • Url in browser localhost/live
  • With my rendered HTML file

I am doing something wrong ?

CodePudding user response:

Request via AJAX, and send html content as string, then write it to document.

Front-End code:

fetch('/your-route')
    .then(response => response.text())
    .then(data => {
        document.write(data)
    })

CodePudding user response:

When using .location you are only setting the response header field of location to be equal to /live. You would have to add a status code of 302 to actually change the url. But when adding a status code of 302 you would cause a redirect and the send file will not be shown as the browser will try to GET /live. So you have to have a listener for GET /live that returns your html file. Or you could directly use res.redirect to redirect to the in that case needed /live handler.

  • Related