简体   繁体   English

使用 GitHub API 创建要点

[英]Create a gist using GitHub API

I wanna create a gist using GitHub API.我想使用 GitHub API 创建一个要点。 I tried an POST ajax request:我尝试了 POST ajax 请求:

var gist = {
    "description": "Avatars",
    "public": true,
    "files": {
        "check.txt": {
            "content": "Avatars list..."
        }
    }
};

$.ajax({
    url: 'https://api.github.com/gists',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(gist),
    success: function(e) {
      console.log(e);
    },
    error: function(e) {
      console.error("Error!: ", e);
    }
});

But I always get the following error:但我总是收到以下错误:

jquery-3.1.1.min.js:4 POST https://api.github.com/gists 401 (Unauthorized)

Can anyone help me?谁能帮我? Thanks谢谢

When you want to edit things on Github, you need to authorize your request.当你想在 Github 上编辑东西时,你需要授权你的请求。 Either by adding a username and password to the request or an oauth token.通过向请求或 oauth 令牌添加用户名和密码。

More information can be found in the authorization documentation: https://developer.github.com/v3/auth/更多信息可以在授权文档中找到: https ://developer.github.com/v3/auth/

Since I ran across the same problem recently, let me add the examples requested by T.Todua由于我最近遇到了同样的问题,让我添加 T.Todua 要求的示例

If you want to authenticate with username and password, add the following lines to your $.ajax request:如果您想使用用户名和密码进行身份验证,请将以下行添加到您的 $.ajax 请求中:

crossDomain: true,
beforeSend: function (XHR) {
  XHR.setRequestHeader(
    'Authorization','Basic ' + btoa(Username + ':' + Password)
  );
},

If, however, you created an access token for your gists (see Github help and don't forget to check the "Gist" permission!) then add the following lines instead但是,如果您为要点创建了一个访问令牌(请参阅Github 帮助并且不要忘记检查“要点”权限!)然后添加以下行

crossDomain: true,
headers: {
  'Authorization':'bearer ' + GitHubAccessToken
},

The GitHubAccessToken will be shown once (and only once,) immediately after creation. GitHubAccessToken 将在创建后立即显示一次(且仅显示一次)。 so make sure to store it in a safe location as everybody knowing this access token will be able to modify your gists (until you revoke it again).所以请确保将它存储在一个安全的位置,因为每个人都知道这个访问令牌将能够修改你的要点(直到你再次撤销它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM