使用JavaScript的Github-Api v3出现问题

时间:2018-12-28 13:27:18

标签: javascript api github github-api github-api-v3

对于家庭作业(在Signavio Workflow Accelerator中),我需要使用GitHub-API v3将用户添加到Github上的组织中。该代码必须用JavaScript编写,而JavaScript是我不太熟悉的语言。

此刻,我得到以下错误代码:“ SyntaxError:JSON在Request._callback位置1处出现意外令牌o”。因此,我感到解析可能存在问题。

var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'

request({url: link, method: 'put', headers: {'User-Agent': 'request'}, auth: {username: token}, JSON: true},
  function (response, body) {
    console.log(body)
    if(body !== undefined){
      body = JSON.parse(body)
      body['state'][0]['main']
      status = body['main']['state']
      status = body.main.state
    }
    else{
      status = 'error'
    }
  })

我不知道这是否有帮助,但是如果我使用cURL执行此put请求,它将起作用,并且答案以

开头
    {
      "url": "https://api.github.com/orgs/myorganization/memberships/githubUser",
      "state": "pending",
  ...}

所以这个“状态”是我想在上面的代码中读取的值。

已经感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我和一个朋友一起工作,一起找到了一个可行的解决方案。因此,如果其他任何人都在同样的挣扎中:这段代码确实神奇!

var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
  const options = {
      url: link,
      method: 'put',
      headers: {'User-Agent': 'request'}, auth: {username: token}
  }
  function callback(error, response, body) {
    console.log(error)
    if(!error && response.statusCode == 200){
      const info = JSON.parse(body)
      status = info['state'][0]['main']
      console.log(status)
      status = info['state']
      status = info.state
    }
    console.log(body)
  }
  request(options, callback)
相关问题