How to render to new HTML page on success of API f

2019-08-28 19:15发布

问题:

I want to render a new HTML page on user request, which is only accessible if the authorization header is set correctly. I initially thought that the browser would redirect to the page, but found out that this is not the case. I have found some ways to handle this, for example replacing the DOM, but I don't think that is a good solution.

Here is the fetch call from UI, which returns the HTML, but does not render it currently:

fetch('/protected_route', {
  headers: {
    'authorization': 'Bearer ' + sessionStorage.getItem('token')
  }
}).then(response => {
  // What to do with the response
});

Here is the server code, if that helps:

app.get('/protected_route', (req, res) => {
  const bearer = req.headers['authorization'];

  if(typeof bearer === 'undefined') {
    res.json({message: 'Not logged in'});
  }
  else {
    const token = bearer.split(' ')[1];

    jwt.verify(token, config.secret, (error, data) => {
      if(error) {
        res.json({message: 'Error verifying token'});
      }
      else {
        res.render('protected_route');
      }
    });
  }
});

回答1:

The problem you are facing is when you tried to open a new HTML page and send back an html file via res.render(), this will send HTML content back to request. When using API call via AJAX or fetch or request or any other API client they are developed for single page application and these calls prohibits browser from rendering to new html page. API calls from such sources process over data and browser have no control over response received.

If you need to render another HTML page than use form-submit to call API, as this is the only way that let browser act upon response, and display response in new page. Since res.render() returned HTML file content, thus a new page act like a file is opened.

If you want to use single page application then you had to process over HTML received in response and then replace whole loaded HTML with new one, you had to make changes in DOM if need to use some API call module.

You can check this github project explaining all basic front-end and backend links for starters.



回答2:

The only way to solve it I've found is using document.write(data). This statement result in rendering the received page but inside the same document, not changing the browser window to the new page and not including a new enter in the history of the browser