12
12

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.

json を返すくせに CORS や jsonp 対応してない APIのための簡単 node.js proxy

Last updated at Posted at 2014-11-10

ある API を使って js で single page app を実装しようかなと思ったら、 CORS や jsonp に対応していなくて残念だったので、 node.js で proxy っぽいものを実装してみました。

クライアント js から外部の API へアクセスするときはこんな感じ。

$.get("/proxy?url=" + encodeURIComponent(apiUrl), function(result) {
    // Do somthing with the result.
});

アプリケーション本体の html, js など静的リソースは /app 以下に配置です。

proxy.js
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();

app.get('/proxy', function(req, res) {
  var url = req.query.url;
  var x = request(url);
  req.pipe(x);
  x.pipe(res);
});
app.use('/', express.static('app'));

var server = app.listen(8000, function(a) {
  console.log(a);
  console.log(server.address());
});
12
12
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?