Express + Node + Mailchimp:未定义请求

时间:2020-07-27 19:56:28

标签: node.js express passport.js

我正在尝试使用passport-mailchimp为已通过Google OAuth2通过PassportJS进行身份验证的用户获取Mailchimp访问令牌。

但是,我一直在Mailchimp回调中遇到ReferenceError: req is not defined。我已经调用serializeUserdeserializeUser来将信息存储在会话中,但是由于某种原因,我无法通过回调函数req.user来授权当前用户。

关于Mailchimp策略为何无法访问当前用户,我是否缺少某些内容?


auth.js

  app.get(
    "/auth/mailchimp",
    passport.authenticate("mailchimp")
  );

  app.get(
    "/auth/mailchimp/callback",
    passport.authenticate("mailchimp", (req, res) => {
      res.redirect('/')
    })
  );

passport.js

passport.use(
  new MailchimpStrategy(
    {
      clientID: keys.mailChimpClientID,
      clientSecret: keys.mailChimpClientSecret,
      callbackURL: "http://127.0.0.1:3000/auth/mailchimp/callback",
      proxy: true
    },
    (accessToken, refreshToken, profile, done) => {
      process.nextTick(function () {
        User.findOneAndUpdate(req.user).then(
          user.mailChimpToken = accessToken,
        )
        .save()
        .then(user => done(null, user));
      });

    }
  )
);

server.js

const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
const cookieSession = require("cookie-session");
const bodyParser = require("body-parser");
const path = require('path')

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const auth = require("./routes/api/auth");
const posts = require("./routes/api/posts");

require("./models/User.js");

app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: ["somesecretkeys"]
  })
);

// MongoDB configuration
const db = require("./config/keys").mongoURI;

// Use mongoose to connect to mongoDB
mongoose
  .connect(db)
  .then(() => console.log("MongoDB connected successfully!"))
  .catch(err => console.log(err));

// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
  console.log('serialize: ' + user.UserId)
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  console.log('deserialize: ' + id)
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
// Passport config
require("./config/passport");

//Use routes from routes folder
//app.use("/api/auth", auth);
//app.use("/api/posts", posts);

require("./routes/api/auth.js")(app);
require("./routes/api/posts.js")(app);

0 个答案:

没有答案