简体   繁体   中英

How to render after authentication with JWT

Application in Nodejs and Express. Authentication with JWT. I have implemented the authentication system with JWT and with Postman it works perfectly. The problem comes when after passing the request authentication middleware and go through the controller that manages the GET of the page I want to render, I receive the response and deal with res.text () that returns a string of text. In the text string I get the full page I want, I render it with document.write (resBody), this updates the content with the new page but does not update neither the history nor the browser window, which is a little bit botched. Is there any way to render the response in javascript? Thank you

// index.hbs
...
...
...
<form id="enter"  enctype="multipart/form-data" name="enter">
    <input type="submit" value="Entrar"> 
</form>

<script type="text/javascript">
    const formEnter = document.querySelector('#enter')
    formEnter.addEventListener('submit',function(event){
        token = "Bearer " + localStorage.getItem('token')
        fetch('/api/brands',{
            method:'get',
            headers: {
                'Content-Type':'application/json;charset=UTF-8',
                'Authorization': token
            }
    .then(function(response) {
       return response.text()
    }).then(resBody => {
       document.write(resBody)  //<--- resBody tiene la página que quiero renderizar
    })
</script>


//brandCtrl.js

...
...


function getBrands(req,res){
    Brand.find({}, (err,brands) => {
        if (err) return res.status(500).send({message: `Error en la petición: ${err}`})
        if (!brands) return res.status(404).send({message: `No se existen Marcas en la BD`})

        res.locals.brands = brands
        res.render("brands/brands",res.locals.brands)
    })
}


...
...

Not sure what do you mean by "render the response in javascript". You can either expect your node application to return a json response (using res.json(YOUR RESPONSE JSON)) or render a template (res.render('some template')) on authenticating successfully.

You are not using fetch API correctly. Your request expects a JSON response , but you are sending an html string as a response.

If you want to render the html page using javascript. you can use jquery:

$('body').load( url,[data],[callback] ); 

You can checkout the documentation here. http://api.jquery.com/load/#urldatacallback

Then you can change the browser history by using history.pushState . But all of this is already done by any frontend framework. So either use one or do this manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM