Home > Software design >  Express Redirection
Express Redirection

Time:10-04

I'm trying to redirect the user after the signup has been validated. See the code below, it never worked with everything i have tried. I also tried on the front end part with

<Redirect=to"/login" />

it wasn't a success either. I'm trying to redirect to : http://localhost:3000/login, the backend is currently on port 5000. I also that those errors coming in the console :

Access to XMLHttpRequest at 'http://localhost:3000/login' (redirected from 'http://localhost:5000/users/signup') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET http://localhost:3000/login net::ERR_FAILED

createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:99) 

My first thought was that the header is not set, but it is in my app.js

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PUT, DELETE, PATCH, OPTIONS"
  );
  next();
});

Thanks in advance

exports.signup = (req, res) => {
  bcrypt.hash(req.body.password, 10).then((hash) => {
    const user = {
      lastName: req.body.lastName,
      firstName: req.body.firstName,
      email: req.body.email,
      password: hash,
    };
    User.create(user)
      .then(() => {
        res.redirect(301, 'http://localhost:3000/login');
      })
      .catch((error) => res.status(500).json({ message: "Impossible de créer l'utilisateur. "   error }));
  });
};

CodePudding user response:

res.status(200).redirect('login');

(EDIT) This will return 200 and redirect the user from the backend.

This is my solution from the front-end, if you'd like it.

On the frontend, you could redirect to your desired location using window.location.replace('/login') after the express returns a value.

What I mean by this is after you've validated the user on your Express API, return 200 via res.status(200).send() to let your front end know that this user is allowed to be redirected.

An example with jQuery:

Front-End

<script>
$.get('http://localhost:3000/login', function(data, status, jqXHR) {
    if (status === 200) {
         window.location.replace('redirect-location.html')
    } else {
        // What to do if the status isn't 200
    }
})
</script>

Back-End:

app.get('/login', (res, req, err) => {
     // Validate
     const result = validatefunction() // true if login matches, false otherwise
    if (result) {
        res.status(200).send()
    } else if (!result) {
        res.status(400).send()
    } else {
        res.status(500).send() 
    }
})

Hope I've helped.

  • Related