LoginSignup
5
4

More than 5 years have passed since last update.

[ConoHa API] JavaScriptからConoHa APIを使う

Last updated at Posted at 2015-07-05

JavaScriptからversionにアクセス

早速JavaScriptからversionにアクセスしてみます。スクリプトは以下の様な感じにしました。

<script>
var url = "https://identity.tyo1.conoha.io/v2.0";
var type = "GET";

var access = function() {
    $.ajax({
      url: url,
      type: type,
      success: function(data) {
        $('#output').text(JSON.stringify(data));
      },
      error: function() {
        console.log('$.ajax error');
      }
    });
}

$(function(){
  access(); 
});
</script>

$.ajaxにURLとアクセスコマンドを入れて、成功時と失敗時のコールバック関数を登録しています。成功時にはHTML内のid='output'というdivタグに受け取ったデータを書き込みます。

Chromeを開いて、バージョンよ来い!と願うも以下のエラーが発生。

XMLHttpRequest cannot load https://identity.tyo1.conoha.io/v2.0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

これはAPIのドメインとアクセスしようとしているHTMLのドメインが異なることから発生するエラーです。Chromeがセキュリティーのためにそういうアクセスを禁止している訳ですね。

JSONPでアクセス

この場合、JSONPでアクセスするとだいたい大丈夫です。早速JSONPにしてみましょう。

var url = "https://identity.tyo1.conoha.io/v2.0?callback=?";
var type = "GET";

var access = function() {
    $.ajax({
      url: url,
      type: type,
      dataType: 'jsonp',
      success: function(data) {
        $('#output').text(JSON.stringify(data));
      },
      error: function() {
        console.log('$.ajax error');
      }
    });
}
Uncaught SyntaxError: Unexpected token :

うーん、サーバ側がJSONPに対応していないようです。。。

回避策

最終的にはPhoneGapからAPIを呼びますが、その際'Access-Control-Allow-Origin' エラーは発生しません。なので、当面Chrome上で問題回避できればそれで良いわけです。

幸い、以下のパラメータを付けてChromeを起動すると今回のエラーが発生しなくなります(セキュリティーが下がってしまいますが)。

--disable-web-security

Macではターミナルから以下のように起動します。

open -a Google\ Chrome --args --disable-web-security

これでJSONのコードでアクセスすると…

{"version":{"status":"stable","updated":"2015-05-12T09:00:00Z","media-types":[{"base":"application/json"},{"base":"application/xml"}],"id":"v2.0","links":[{"href":"https://identity.tyo1.conoha.io/v2.0/","rel":"self"},{"href":"https://www.conoha.jp/docs/","type":"text/html","rel":"describedby"}]}}

キタっ

これで安心してJavaScriptからAPIを使用できます。次はトークンの発行とVM情報の取得を行います。

今回のコードはGitHubにおいてあります。

5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4