LoginSignup
2
1

More than 3 years have passed since last update.

N予備校の教材でAjaxでCORSを試してみる

Posted at

やりたいこと

N予備校のAjaxのページに「同一生成ポリシーを満たさない場合CORSにひかかって通信できません」と書かれているが、そのあたりの回避策について特に紹介されていなかったのでAccess-Control-Allow-Originを試してみる。

前提知識

環境

  • Vagrant ubuntu(Node.jsにて上記のリンクのサーバが稼働している)
  • 手元のマシン(Mac)

実験

  • 手元のマシンのブラウザから、Vagrant上のNode.jsに対してAjax通信を行い失敗することを確認する
  • CORSを回避するためにサーバー側にヘッダーを挿入する

修正前

  • LoadAvgが表示されない
  • コンソールログをみると以下のエラーが発生している
Access to XMLHttpRequest at 'http://localhost:8000/server-status' 
from origin 'http://localhost' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

コード修正

server-status.js

'use strict';
const express = require('express');
const router = express.Router();
const os = require('os');

router.get('/', (req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost')  👈追加
  res.json({ loadavg: os.loadavg() });
});

module.exports = router;

Access-Control-Allow-Originを追加することで特定のOriginからの通信を許容する

修正後

  • LoadAvgが表示された

Access-Control-Allow-Origin: http://localhost 👈 追加されている
Connection: keep-alive
Content-Length: 19
Content-Type: application/json; charset=utf-8
Date: Tue, 24 Mar 2020 19:25:17 GMT
ETag: W/"13-78iQH47CLcJ0F+4s06WtpVC9PNc"
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
2
1
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
2
1