Fetch: How to manage a redirect request in fetch

Created on 4 May 2016  路  1Comment  路  Source: github/fetch

I am using fetch to communicate with the node server(Express). I am building a SPA. On each request to the server I am checking if the session is valid or not. If the session is not valid I am redirecting from node to a login page. The problem is that. If the session is getting invalidated(for eg: get/post request running in the background without a page refresh) the request is failing silently. It is not getting redirected.

I had the same issue for the ajax request also. What I had done is by checking the request is xhr and accept json. Then send a json response and handle the redirect in the frond end.

if (req.xhr && req.accepts('json')) {
  res.json({status:'session_timeout'});
}else{
  res.redirect('/login');
}

How can I do the same by using fetch. How do I handle redirect using fetch.

>All comments

Hi @jetsonjohn. This is really a usage question and we can't really write your application for you. We don't know what all the intricacies of your authentication system need to be.

From your server-side code example, it seems that you're doing things right. All what's left is that whenever you make a fetch() request, you need to parse its JSON response and check for whether the status key is equal to "session_timeout", then perform the redirect to /login manually. Which our examples in the README for how to parse JSON from responses.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gkatsanos picture gkatsanos  路  4Comments

xgqfrms-GitHub picture xgqfrms-GitHub  路  4Comments

huanghaiyang picture huanghaiyang  路  3Comments

kocur4d picture kocur4d  路  3Comments

fczuardi picture fczuardi  路  3Comments