はじめに
CORS問題に関して、対策がわからなかったので勉強しました。
今回はReactで試していませんがゆくゆく使えるようにしたいです。
※今回はソースコードだけ載せておきます。
セットアップ
パッケージのインストール
$ npm i express http-proxy
ソースコード
server.js
const http = require("http"); const httpProxy = require("http-proxy"); const Express = require("express"); // インスタンス作成 const app = new Express(); const server = new http.Server(app); // プロキシサーバーを定義 const proxy = httpProxy.createProxyServer({ target: 'http://localhost:3001' }); // ルートへのアクセス時のレスポンス app.get("/", (req, res) => { res.send("Hello, Express"); }); // /apiでプロキシサーバー(localhost:3001)にアクセス app.use("/api", (req, res) => { proxy.web(req, res); }); // ポート3000をWebサーバーとして起動 server.listen(3000, () => { console.info("WebServer running on http://localhost:3000"); });
apiServer.js
const http = require('http'); const fs = require('fs'); const url = require('url'); const json = fs.readFileSync('./sample.json', 'utf8'); // ポート3001をJSONサーバーに。 var server = http.createServer(getFromClient); server.listen(3001); console.log('JSON Server start!'); // createServerの処理 function getFromClient(request, response){ var url_parts = url.parse(request.url, true); switch (url_parts.pathname) { case '/': response.write(json); response.end(); break; default: response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('no page...'); break; } }
sample.json
[ { "name": "メロン", "price": 500, "place": "東京" }, { "name": "スイカ", "price": 400, "place": "宮城" } ]
実行
$ node server $ node apiServer$ node server | node apiServer
※パイプで起動したりするとコマンドライン上で最初に起動したサーバーがキルできなくなるっぽいので注意。
http://localhost:3000/

http://localhost:3000/api

👆3001で起動したJSONデータをレスポンスするサーバーを3000/apiで確認できた◎
テンプレートから読み込む※追記※
server.jsを修正
const http = require("http"); const fs = require('fs'); const httpProxy = require("http-proxy"); const Express = require("express"); // expressのインスタンス作成 const app = new Express(); const server = new http.Server(app); // プロキシサーバーを定義 const proxy = httpProxy.createProxyServer({ target: 'http://localhost:3001' }); // テンプレートの読み込み const html = fs.readFileSync('./index.html', 'utf8'); // ルートへのアクセス時のレスポンス app.get("/", (req, res) => { res.send(html); }); // /apiでプロキシサーバー(localhost:3001)にアクセス app.use("/api", (req, res) => { proxy.web(req, res); }); // ポート3000をWebサーバーとして起動 server.listen(3000, () => { console.info("WebServer running on http://localhost:3000"); });
index.html
<!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery. min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <meta charset="utf-8"> </head> <body> <h1>JSONテスト</h1> <input type="button" value=".ajax" onclick="test()"> <input type="button" value="getJSON" onclick="test2()"> <input type="button" value="axios" onclick="test3()"> <script> 'use strict'; function test() { $.ajax({ url: '/api', dataType: 'json' }) .done(function (data) { console.log(data); }) .fail(function () { console.log('読み込みエラー'); }); }; function test2() { $.getJSON("/api", (data) => { console.log(data); }); }; function test3() { axois.get('/api', resp => { console.log(resp) }) }; </script> </body> </html>
確認

axiosだけ取得できなかったものの(CDNが機能していない??)、jQueryでは取得できた◎
備忘録
axiosのCDN 参考
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
コメントを残す