在NodeJ中成功获取API后,如何呈现到新的HTML页面? [英] How to render to new HTML page on success of API fetch request in NodeJs?

查看:155
本文介绍了在NodeJ中成功获取API后,如何呈现到新的HTML页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户请求呈现一个新的HTML页面,只有正确设置 authorization 标头,该页面才能访问.我最初以为浏览器将重定向到页面,但发现情况并非如此.我发现了一些解决方法,例如替换DOM,但我认为这不是一个好的解决方案.

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.

这是从UI进行的提取调用,该调用返回HTML,但当前不呈现它:

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');
      }
    });
  }
});

推荐答案

您面临的问题是,当您尝试打开新的HTML页面并通过res.render()发送回html文件时,这会将HTML内容发送回要求.通过AJAX或访存或请求或任何其他API客户端使用API​​调用时,它们是为单页应用程序开发的,这些调用禁止浏览器呈现到新的html页面.来自此类来源的API调用会处理数据,浏览器无法控制收到的响应.

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.

如果您需要渲染另一个HTML页面而不是使用form-submit来调用API,则这是让浏览器根据响应进行操作并在新页面中显示响应的唯一方法.由于res.render()返回了HTML文件的内容,因此打开了一个新页面,就像打开一个文件一样.

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.

如果要使用单页应用程序,则必须处理收到的响应HTML,然后用新的HTML替换整个加载的HTML,如果需要使用某些API调用模块,则必须在DOM中进行更改.

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.

您可以检查此github项目,其中介绍了所有基本的前端和后端链接对于初学者.

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

这篇关于在NodeJ中成功获取API后,如何呈现到新的HTML页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆