如何通过 API(非匿名)post 要点

How to post a gist via the API (not anonymously)

我正在使用 passport-github 策略。

passport.use(new Strategy({
    clientID: "...",
    clientSecret: "...",
    callbackURL: 'http://localhost:3000/login/github/return',
    scope: 'gist'
  },
  function(accessToken, refreshToken, profile, cb) {
    return cb(null, profile);
  }));

然后我提出 POST 请求

app.get('/profile/post',
  require('connect-ensure-login').ensureLoggedIn(),
  function(req, res){
var url = 'https://api.github.com/gists';

axios.post(url, {
  method: "POST",
  "description": "POSTING FROM EXPRESS",
  "public": true,
  "files": {
    "file1.txt": {
      "content": "EXPRESS "
    }

}
})
  .then(function (response) {...})
  .catch(function (error) { ... });

要点是匿名创建的。

我尝试将 "owner""user" 作为请求参数的一部分传递,但没有用。我还尝试在 url

中传递用户名

据我所知the docs对此什么都不说。

您必须存储从护照身份验证回调中获得的访问令牌。例如,使用 mongo 和 mongoose 来存储用户:

passport.use(new GitHubStrategy({
        clientID: "...",
        clientSecret: "...",
        callbackURL: 'http://localhost:3000/login/github/return'
    },
    function(accessToken, refreshToken, profile, done) {

        process.nextTick(function() {

            User.findOne({ id: profile.id }, function(err, res) {
                if (err)
                    return done(err);
                if (res) {
                    console.log("user exists");
                    return done(null, res);
                } else {
                    console.log("insert user");
                    var user = new User({
                        id: profile.id,
                        access_token: accessToken,
                        refresh_token: refreshToken
                    });
                    user.save(function(err) {
                        if (err)
                            return done(err);
                        return done(null, user);
                    });
                }
            })
        });
    }
));

然后当你反序列化用户时,你会用访问令牌取回用户:

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findOne({ "id": id }, function(err, user) {
        done(err, user);
    });
});

现在在您的端点中,将 req.user.access_token 放入 github API 请求的 Authorization header 中:

app.get('/profile/post', 
  require('connect-ensure-login').ensureLoggedIn(),
  function(req, res) {

    axios.post('https://api.github.com/gists', {
      "method": "POST",
      "description": "POSTING FROM EXPRESS",
      "headers": {
        "Authorization" : "token " + req.user.access_token
      },
      "public": true,
      "files": {
        "file1.txt": {
          "content": "EXPRESS "
        }
      }
    })
    .then(function (response) {...})
    .catch(function (error) { ... });
  }
);

但是您可以将 passport-github 的 octonode library that do it for you. You can find a complete example here 与 octonode 和 mongodb

一起使用,而不是手动构建请求