Open Res Again to Redirect Express

Login menses is the key to managing websites. To make sure, many users are logged in with their credentials registered in your website, most websites allow just to reveal their content until the user is logged in. This means redirecting the user dorsum to the login page if they are not logged in or have logged out of the session.

Today, in this comprehensive mail service, we will audit in detail how to apply React routers to regulate the menstruum of login/logout through redirecting the pages.

Start thing starting time, I have used express-js remainder API for react in this demonstration.

What is a REST web service?

A Residual(Representational Country Transfer) API proactively manages operability between the client asking and the constraints set up then returns the appropriate HTTP response with the desired functionality.

The nearly pleasing thing about Residual web services is that it is light weighted, embeddable, and consumable with other services.


Restful API services handle your intended awarding and promptly behave out the extensive operations of the client in a secure and stateless manner. But how the proper name states, a transfer of a representation of a
state in a stateless manner.


Let's get started!

In this code, note that two paths take been created.

The requisition "/login" discharges a function that listens to the requests incoming from the user through the post method. For the sake of the purpose, I have assumed the username and password.


The if status checks the request for login, only to be fulfilled by the established criteria of that the req.body.username and req.torso.countersign exists, and the provided username and password match the correct username and password.


If that's the instance and so a token is being generated. This token is granted to the user that has requested to login.

            app.mail service("/login", role(req, res) {   permit username = "[electronic mail protected]";   let password = "12345678";   panel.log(req.body);   if (     (req.trunk.username || req.body.password) &&     username === req.body.username &&     password === req.body.password   ) {     console.log("Success");     let token = btoa(username + countersign);     render res.ship({ token: token });   }   console.log("mistake");   return res.send(req.trunk); });                      

Notice that the token is typically generated by concatenating the username and password then encoding it in base of operations 64 with btoa() method. Through response, the token is sent to the customer to resume his/her session.

All the same, if the username and countersign are not a match and the condition fails, so the introductory requested page is returned. That means back to the login page.

            app.post("/islogin", function(req, res) {   return res.send({     status:       req.headers.say-so &&       req.headers.authorization === "amFtZXNAZ21haWwuY29tMTIzNDU2Nzg="   }); });                      

This path is simpler. Its updating the condition to truthful if the req.headers.Authorization is truthful, and it matches to the token that has only been generated.

When an explicit request is taken in, all the details of information technology are in the header. Who initiated the login, the credentials, type of protocol used, all the details being sent to the server from the browser.

Through this, hallmark is carried out to make sure that the user logged in is authorized.

            <iframe src="https://codesandbox.io/embed/express-js-rest-api-for-react-route-x60t8?fontsize=14&hidenavigation=1&theme=dark"  style="width:100%; pinnacle:500px; border:0; border-radius: 4px; overflow:hidden;" championship="express-js-rest-api-for-react-route"  permit="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts> </iframe>                      

REACT ROUTING

This is a way of implementing the react routing using

<BrowserRouter>, <Switch> and <Route> components. 2 paths are being routed, with the "/", the LogIn component will exist rendered while if the user uses "/domicile" then the Home component volition be rendered.

            import React, { Component } from "react"; import { BrowserRouter, Switch, Route } from "react-router-dom"; import Dwelling from "./Dwelling"; import LogIn from "./LogIn";  consign default grade App extends Component {   render() {     return (       <div className="app">         <BrowserRouter>           <Switch>             <Route exact path={"/"} component={LogIn} />             <Road verbal path={"/home"} component={Home} />           </Switch>         </BrowserRouter>               </div>     );   } }                      

LogIn and Home pages

At present allow'southward take a expect at the React application. To go on things simple, I accept created two components, Login and Home.

Let kickoff go through the Login component, the jsx being rendered of the login class in the browser through the following code. A form is created in which input fields like e-mail and password are generated.

            render() {     return (       <div>         <grade onSubmit={this.c}>           <h1>welcome to log in!</h1>           <br />           <input             type="email"             name="email"             placeholder="E-mail"             defaultValue={this.country.email}             onChange={e => {               this.setState({ email: e.target.value });             }}           />           <br />           <br />           <input             blazon="password"             name="countersign"             placeholder="Password"             defaultValue={this.state.password}             onChange={e => {               this.setState({ countersign: e.target.value });             }}           />           <br />           <br />           <push type="submit"> Login </push>         </form>       </div>     );   }                      

Now when the form is being submitted, handleSubmit is being called. Below I accept divers handleSubmit() that handles the outcome when the user submits the form. event.preventDefault() stops the course from being submitted if information technology's in its default state. At present take a look at the axios.postal service() method.

The URL being hit is that of the Remainder API created above of the path "/login". If you review "/login", it generates a token if the email and password is a friction match. This is how React and the Rest API is interacting through passing the user's request.

            handleSubmit(event) {     result.preventDefault();     const { email, password } = this.state;     // console.log(this.land);      axios       .postal service(         "https://x60t8.sse.codesandbox.io/login",         {           username: electronic mail,           password: password         }         // { withCredentials: true }       )       .then(res => {         console.log(res);         window.localStorage.setItem("token", res.data.token);         this.props.history.push("/home");         // return <Redirect to="/home" />;       })       .grab(err => {         console.log(err);       });   }                      

Once the Rest API responds with a successful match with a token so I have saved the token in the localStorage.

History prop comes from the History Library and has properties related to routing. The push property What information technology does is it pushes a new entry into the history stack and redirects the user to the defined road. In our case, later on a successful login, redirecting the user to the domicile page, else throws an error bulletin and prevents them from submitting.

ComponentDidMount() volition be chosen when all the components of the page has been rendered to the customer-side properly. The outset condition checks if the token exists in the localstorage.

            componentDidMount() {     if (window.localStorage.getItem("token")) {       axios.defaults.headers.common[         "Authorization"       ] = window.localStorage.getItem("token");       axios         .postal service("https://x60t8.sse.codesandbox.io/islogin")         .then(res => {           if (res.data.status) {                         this.props.history.button("/home");           }         })         .grab(res => panel.log(res));     }   }                      

Call up the "/islogin" path that we've defined in the Balance web services, we are hit the "/islogin" path to ship the credentials for authorisation.

When the URL is successfully operational and response is received from the REST service, I have checked that if the status is updated to true. If then so the user will successfully be redirected to the home folio. In case the authorization fails, an error will exist generated and the user volition stay on the login folio.

We've gone through the login page. What about the dwelling house page? The Home component first checks if the token doesn't exists then push the user back to the login folio. If the token's value exists, but so it'southward being sent back to the Residue web service we created for hallmark.

If the response returned from the service in the variable of status is imitation, meaning the user failed the hallmark, he/she will be redirected dorsum to the login page.

            export default class Home extends Component {   componentDidMount() {     if (!window.localStorage.getItem("token")) {       //redirect to Login       console.log("redirect to login");       this.props.history.button("/");     }      if (window.localStorage.getItem("token")) {       axios.defaults.headers.common[         "Authorization"       ] = window.localStorage.getItem("token");       axios         .mail("https://x60t8.sse.codesandbox.io/islogin")         .and then(res => {           console.log();           if (!res.data.status) {             //window.location.href = window.location.toString() + "/habitation";             panel.log("redirct to login");             this.props.history.push("/");           }         })         .grab(res => console.log(res));     }   }                      

Now if the user logs out, the token is being removed from the localstorage and is being pushed back to the login page.

            render() {     render (       <div>         <h1>Dwelling house</h1>         <h1>You are logged in</h1>         <push           onClick={e => {             window.localStorage.removeItem("token");             this.props.history.push("/");           }}         >           Logout         </push>       </div>     );                      

let's try to understand what nosotros have overall covered in the article by understanding the output

First, let'southward try to access the homepage without logging in.

Yous will be redirected dorsum to the login page

react router redirect

At present try to log in, this will redirect y'all to the domicile folio.

With the correct credentials, you are redirected to the home page.

Log out and you will be redirected back to the login webpage. Just the manner we crave.

Conclusion

The React routers can exist used efficiently to direct the user to various pages the programmer desires to connect. They remain an excellent way to have control over the paths of the website that the user might take and employ it in a favorable mode for both the user and developer.

            <iframe src="https://codesandbox.io/embed/tender-volhard-jk0f6?fontsize=14&hidenavigation=1&theme=night" way="width:100%; height:500px; border:0; border-radius: 4px; overflow:subconscious;" title="tender-volhard-jk0f6" permit="accelerometer; ambient-light-sensor; photographic camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr" sandbox="allow-forms allow-modals allow-popups allow-presentation let-same-origin let-scripts"> </iframe>                      

dionslearearal.blogspot.com

Source: https://www.codeleaks.io/how-to-router-redirect-after-login-react/

0 Response to "Open Res Again to Redirect Express"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel