9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

xmlで取得するwebapiをjsonpに置換する

Last updated at Posted at 2014-04-10

GitHub
https://github.com/yoh-nak/xml2jsonp

使い方

XMLで受け取るwebapiをjsonpに置換することでクロスオリジンポリシーを解消することができる仕組みです。

以下のようにアクセスして、URLクエリに指定したコールバック関数名とWeb APIを使ったjsonpを出力することができます。

http://ドメイン:3000/?callback=コールバック関数名&api=APIのURL

! 注意

APIに指定するURLは下記のサイト

などをつかってUTF-8でURLエンコードしたものを使用してください。

たとえば下記のAPIのURLをURLエンコードすると

http://wikipedia.simpleapi.net/api?keyword=HTTP&output=xml

以下のようになります。

http%3a%2f%2fwikipedia%2esimpleapi%2enet%2fapi%3fkeyword%3dHTTP%26output%3dxml

インストール

Express

$ npm install -g express
$ express xml2jsonp
$ cd xml2jsonp
$ npm install

依存パッケージ

$ npm install xmljson --save

ソースコード

package.json
{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.8",
    "jade": "*",
    "stylus": "*",
    "xmljson": "^0.2.0"
  }
}
app.js

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
routes/index.js

/*
 * GET home page.
 */

exports.index = function(req, res){

    var xml2jsonp = require('../libs/xml2jsonp');
    xml2jsonp.convert(req, res);

};
libs/xml2jsonp.js

var http = require('http');
var xmljson = require('xmljson');

exports.convert = function(req, res){

    var testUrl = 'http://wikipedia.simpleapi.net/api?keyword=HTTP&output=xml';

    var api = decodeURIComponent(req.query.api) ? decodeURIComponent(req.query.api) : testUrl;
    var callback = req.query.callback ? req.query.callback : 'callback';

    var xml = '';

    http.get(api, function(response) {

        response.setEncoding('utf8');
        response.on('data', function(str) {
            xml += str;

            xmljson.to_json(xml, function (error, data) {

                var jsonp = callback + '(' + JSON.stringify(data) + ')';
                
                res.header('Content-Type', 'text/javascript; charset=UTF-8');
                res.send(jsonp);

            });
        });
    }).on('error', function(e){
        console.log(e.message);
    });
}
9
9
0

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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?