POST路由中的req.session为空

时间:2018-01-28 16:37:59

标签: javascript node.js express session cookie-session

我正在使用passport.js谷歌oAuth20以及cookie会话中间件,但每当我console.log(req.session)它是{}(空)时,它只发生在POST路由

这是路线

  app.post("/addTodo", (req, res) => {
    console.log("POST", req.session);
    // UserSchema.findOne({ _id: req.session.passport.user }, function(err, res) {
    //   res.todos.push({ name: req.body.todo, isCompleted: false });
    //   res.save((err, value) => {});
    // });
    res.send("Add todo");
  });

这是我的护照策略:

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const mongoose = require("mongoose");

const User = mongoose.model("UserSchema");
passport.serializeUser((user, done) => {
  console.log("serializeUser");
  done(null, user.id);
});
passport.deserializeUser((id, done) => {
  User.findById(id, function(err, user) {
    console.log("deserializeUser");
    done(err, user);
  });
});
passport.use(
  new GoogleStrategy(
    {
      clientID:
        "hidden for security concerns",
      clientSecret: "hidden for security concerns",
      callbackURL: "http://localhost:5000/auth/google/callback"
    },

    async (accessToken, refreshToken, profile, done) => {
      const existingUser = await User.findOne({ googleId: profile.id });

      if (existingUser) {
        return done(null, existingUser);
      }

      const user = await new User({
        googleId: profile.id,
        email: profile.emails[0].value
      }).save();
      done(null, user);
    }
  )
);

我在index.js中的中间件如下:

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: ["abc"]
  })
);
app.use(passport.initialize());
app.use(passport.session());

basicRoutes(app);
authRoutes(app);
const port = process.env.PORT || 5000;
app.listen(port);

我遇到了cors问题所以我安装了这个cors plugin,我在通过客户端和邮递员发送时都遇到了问题。

提前感谢您的时间和关注。

0 个答案:

没有答案