使用GitHub API调用“ config”包时,我未定义“ githubClientID”

时间:2019-08-12 09:26:18

标签: javascript postman github-api

我正在创建一项功能,用于通过GitHub API检索GitHub用户名。

从Postman发送GET请求时,出现服务器错误,显示为:

  

“未定义配置属性“ githubClientId””

尽管我使用config中定义的githubClientID来调用config/default.json程序包,如下所示:

{
  "mongoURI": "mongodb+srv://massas:oir@socialapp-2dg3r.mongodb.net/test?retryWrites=true&w=majority",
  "jwtToken" : "oecret",
  "githubClientId:": "ID",
  "githubSecret": "SECRET"
}
// change the values for public viewing

以下是调用API的代码:

const express = require('express');
const request = require('request');
const config = require('config');

// @route       GET api/profile/github/:username
// @desc        Get user repos from username
// @acess       Private
router.get('/github/:username', (req, res) => {
  try {
    const options = {
      uri: `https://api.github.com/users/${
          req.params.username
        }/repos?per_page=5&sort=created:asc&client_id=${config.get(
          'githubClientId'
        )}&client_secret=${config.get('githubSecret')}`,
      method: 'GET',
      headers: {
        'user-agent': 'node.js'
      }
    };
    request(options, (error, response, body) => {
      if (error) console.error(error);
      if (response.statusCode !== 200) {
        return res.status(404).json({
          msg: 'No Github profile found'
        });
      }
      res.json(JSON.parse(body));
    });
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

1-您需要从以下位置更改选项对象:

const options = {
  uri: `https://api.github.com/users/${
      req.params.username
    }/repos?per_page=5&sort=created:asc&client_id=${config.get(
      'githubClientId'
    )}&client_secret=${config.get('githubSecret')}`,
  method: 'GET',
  headers: {
    'user-agent': 'node.js'
  }
};

收件人:

const uri = encodeURI(
  `https://api.github.com/users/${req.params.username}/repos?per_page=5&sort=created:asc`
);
const headers = {
  'user-agent': 'node.js',
  Authorization: `token ${config.get('githubToken')}`
};

const gitHubResponse = await axios.get(uri, { headers });

2-确保使用您的GitHub秘密访问令牌在config文件夹中添加default.json文件

{ "githubToken": "<yoursecrectaccesstoken>" }

3-如果没有安装axios,请在项目的根目录中安装

npm i axios