首页 > 解决方案 > 处理竞争条件:护照注册功能有效,但响应 404 错误

问题描述

出于某种原因,我收到此代码的 404 错误响应。它首先执行成功的 204 注册,然后执行 404 错误。奇怪的是,正在我的数据库中创建用户,正在创建会话,并且用户对象正在填充 req.user。所以一切正常,但我在前端收到 404 错误。

前端

signUp: async (email, password) => {
        const res = await fetch("http://localhost:3000/signUp", {
          body: JSON.stringify({ email: email, password: password }),
          mode: "cors", // no-cors, cors, *include
          cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
          credentials: "include", // include, *include, omit
          headers: {
            "content-type": "application/json",
          },
          method: "POST",
        }).catch(error => this.setState({ isError: true }))
        if (res.ok) {
          this.setState({ isAuthenticated: true, isError: false })
        } else {
          console.log(res.status)
//this is running
          this.setState({
            isError: true,
          })
        }

后端:

 app.post(
    "/signUp",
    (req, res, next) => {
      const email = req.body.email;
      const password = req.body.password;

      User.findOne({ email: email }, function(err, user) {
        if (err) {
          console.log(err);
          return next(err);
        }
        if (user) {
          return res.send({ message: "User Already Exists" });
        }
        const newUser = new User({
          email: email,
          password: password
        });
        newUser.save(next);
      });
    },
    passport.authenticate("login")
  );

标签: javascriptnode.jsreactjspassport.js

解决方案


我在这里有两个问题:

  1. 您在这里使用哪种策略?..因为您使用了 passport.authenticate('login').. 我不记得有这样的策略
  2. 你为什么最后使用passport.authenticate()?..因为通常passport.authenticate()会在中间件中..

所以我假设,您正在尝试在login路线中使用护照进行身份验证。因此,尝试编写如下内容:

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login' }));

推荐阅读