如何将不和谐的OAuth连接到我的网站

时间:2020-02-02 21:19:02

标签: javascript oauth

我正在尝试通过此处的this教程将OAuth Discord链接连接到我的网站,并且一切运行正常,直到我将文件添加到目录的一部分,并且我想知道是否必须参考该文件位于同一目录的server.js文件中

const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');


const router = express.Router();

const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect = encodeURIComponent('http://localhost:50451/api/discord/callback');

router.get('/login', (req, res) => {
  res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=<my-id-goes-here>&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds.join%20webhook.incoming`);
});


router.get('/callback', catchAsync(async (req, res) => {
    if (!req.query.code) throw new Error('NoCodeProvided');
    const code = req.query.code;
    const creds = btoa(`my-id-goes-here:my-secret-goes here`);
    const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
      {
        method: 'POST',
        headers: {
          Authorization: `Basic ${creds}`,
        },
      });
    const json = await response.json();
    res.redirect(`/?token=${json.access_token}`);
  }));

module.exports = router;

我的discord.js文件,该文件位于与其他两个文件夹不同的文件夹中

// async/await error catcher
const catchAsyncErrors = fn => (
  (req, res, next) => {
    const routePromise = fn(req, res, next);
    if (routePromise.catch) {
      routePromise.catch(err => next(err));
    }
  }
);

exports.catchAsync = catchAsyncErrors;

我的utils.js文件,与server.js位于同一文件夹中

const express = require('express');
const path = require('path');

const app = express();

app.get('/', (req, res) => {
  res.status(200).sendFile(path.join(__dirname, 'index.html'));
});

app.listen(50451, () => {
  console.info('Running on port 50451');
});


app.use('/api/discord', require('../api/discord'));



app.use((err, req, res, next) => {
    switch (err.message) {
      case 'NoCodeProvided':
        return res.status(400).send({
          status: 'ERROR',
          error: err.message,
        });
      default:
        return res.status(500).send({
          status: 'ERROR',
          error: err.message,
        });
    }
  });

 //app.use('/utils', require('utils'))-Mabye this part needs to be in here, 

我的server.js文件

0 个答案:

没有答案