How to render to new HTML page on success of API fetch request in NodeJs?











up vote
0
down vote

favorite












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









share|improve this question




















  • 3




    fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
    – Chris G
    Nov 19 at 20:47












  • @ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
    – leonphil
    Nov 19 at 21:01

















up vote
0
down vote

favorite












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









share|improve this question




















  • 3




    fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
    – Chris G
    Nov 19 at 20:47












  • @ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
    – leonphil
    Nov 19 at 21:01















up vote
0
down vote

favorite









up vote
0
down vote

favorite











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









share|improve this question















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






javascript html node.js express fetch






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 23:03









NAVIN

1,5923623




1,5923623










asked Nov 19 at 20:42









leonphil

32




32








  • 3




    fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
    – Chris G
    Nov 19 at 20:47












  • @ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
    – leonphil
    Nov 19 at 21:01
















  • 3




    fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
    – Chris G
    Nov 19 at 20:47












  • @ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
    – leonphil
    Nov 19 at 21:01










3




3




fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
– Chris G
Nov 19 at 20:47






fetch runs an HTTP request but it's meant to communicate with the server without leaving the current page. Since you're handling the authorization manually anyway, why not use a cookie instead? That way you can check the cookie in your /protected_route handler, then simply use an <a> to let the user move to the page.
– Chris G
Nov 19 at 20:47














@ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
– leonphil
Nov 19 at 21:01






@ChrisG Thanks for the answer! I actually did not consider that option. I just redirected the user with window.location.href=path and it works now.
– leonphil
Nov 19 at 21:01














1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










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.






share|improve this answer



















  • 1




    These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
    – Chris G
    Nov 19 at 21:54






  • 1




    What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
    – Chris G
    Nov 19 at 21:57








  • 1




    If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
    – Chris G
    Nov 19 at 22:02






  • 2




    That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
    – NAVIN
    Nov 20 at 6:52










  • Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
    – Chris G
    Nov 20 at 9:53













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382339%2fhow-to-render-to-new-html-page-on-success-of-api-fetch-request-in-nodejs%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










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.






share|improve this answer



















  • 1




    These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
    – Chris G
    Nov 19 at 21:54






  • 1




    What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
    – Chris G
    Nov 19 at 21:57








  • 1




    If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
    – Chris G
    Nov 19 at 22:02






  • 2




    That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
    – NAVIN
    Nov 20 at 6:52










  • Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
    – Chris G
    Nov 20 at 9:53

















up vote
1
down vote



accepted










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.






share|improve this answer



















  • 1




    These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
    – Chris G
    Nov 19 at 21:54






  • 1




    What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
    – Chris G
    Nov 19 at 21:57








  • 1




    If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
    – Chris G
    Nov 19 at 22:02






  • 2




    That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
    – NAVIN
    Nov 20 at 6:52










  • Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
    – Chris G
    Nov 20 at 9:53















up vote
1
down vote



accepted







up vote
1
down vote



accepted






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.






share|improve this answer














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.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 11:25

























answered Nov 19 at 20:59









NAVIN

1,5923623




1,5923623








  • 1




    These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
    – Chris G
    Nov 19 at 21:54






  • 1




    What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
    – Chris G
    Nov 19 at 21:57








  • 1




    If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
    – Chris G
    Nov 19 at 22:02






  • 2




    That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
    – NAVIN
    Nov 20 at 6:52










  • Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
    – Chris G
    Nov 20 at 9:53
















  • 1




    These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
    – Chris G
    Nov 19 at 21:54






  • 1




    What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
    – Chris G
    Nov 19 at 21:57








  • 1




    If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
    – Chris G
    Nov 19 at 22:02






  • 2




    That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
    – NAVIN
    Nov 20 at 6:52










  • Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
    – Chris G
    Nov 20 at 9:53










1




1




These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
– Chris G
Nov 19 at 21:54




These response function can only send back data and not html file to be clear: the server can absolutely send back an HTML file here, and it won't even be able to tell the difference between an AJAX request and the regular way. All it does is provide endpoints for requests. It is perfectly possible to (nonsensically) have the browser navigate to a JSON file, or to request and process an HTML file via AJAX.
– Chris G
Nov 19 at 21:54




1




1




What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
– Chris G
Nov 19 at 21:57






What res.render() does is call the view engine, supplying a view file and optional parameters, then send back the resulting file, usually HTML. Again, replying with res.render() to an AJAX request is perfectly possible and can in fact be a useful implementation. The important thing any answer to the above question must include is that fetch is unsuitable when it comes to navigating programmatically using JS.
– Chris G
Nov 19 at 21:57






1




1




If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
– Chris G
Nov 19 at 22:02




If you need to render another html page than use form-submit to call API as this is the only way that let server render to other page No, one can use location.href = url; to navigate elsewhere. Plus, again, the server only provides the reply. Whether the browser renders it or not depends on how the request was made, not on the commands the server-side code used.
– Chris G
Nov 19 at 22:02




2




2




That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
– NAVIN
Nov 20 at 6:52




That's what i been trying to say that these functions doesn't allow browser to display response provided by server and act as a middle ware to manipulate the data. And we had to make changes in DOM to reflect changes on HTML and we can append, replace old HTML with HTML provided in response.
– NAVIN
Nov 20 at 6:52












Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
– Chris G
Nov 20 at 9:53






Sorry, but your answer contains several statements that are plain wrong, and is very misleading. In my book it shows you know how to use the commands you reference, but you don't truly understand the processes involved. OP marked it as accepted, probably without really reading it, but it should be edited or removed imo.
– Chris G
Nov 20 at 9:53




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382339%2fhow-to-render-to-new-html-page-on-success-of-api-fetch-request-in-nodejs%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

If I really need a card on my start hand, how many mulligans make sense? [duplicate]

Alcedinidae

Can an atomic nucleus contain both particles and antiparticles? [duplicate]