简体   繁体   中英

How could back-end (PHP) force redirect on ajax call?

Sorry for maybe stupid/easy/naive question but I'm having a React headless app which obviously does a lot of data fetching.

Sometimes some requests have a status of 4xx or 5xx.

Is there a universal way of doing a redirect to a given url when this occur without touching the front-end layer?

So when I go to mypage.example.com/user/134, fetch data, get 404 returned, could the back-end itself trigger redirect to user/1?

I know I could do that with routing but there are hundreds of routes and I don't have access to the front-end repos yet, wondered if something like this is achievable from the back? Maybe if there's a 404 back-end should send something with header with location set or something like that?

$.ajax({
   //code
}).then(function(response){
   //action on success
}).catch(function(error){
   console.log(error)
   //do what ever you want to with error
   //then redirect to another page
   window.location.href="http://url"
})

I think there are a couple of ways of doing this - You could try writing a custom fetch hook or a wrapper for fetch that always redirects to a particular route based on the response status?

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