29
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

ChromeでAjax通信時にエラー発生したときのメモ

Ajax通信時に「provisional headers are shown」エラーではまったメモ

script.coffee
$.ajax({
  url: "http://example.com/ajax.php",
  type: "POST",
  dataType: datatype,
  cache: false,
  data: {'test':'test'},
  })
ajax.php
<?php
# URL : http://hoge.example.com
$data = array("res"=>"responce");
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);
?>

example.com も hoge.example.com 同一IPなので問題ないと思ったがクロスドメインと判定されエラーになっている。

この場合はhoge.example.comをexample.comに直せば改善するが
異なったドメインにアクセスするにはサーバーをCORS対策するかJSONNPで

nginx CORS設定

nginx.conf
#
# CORS header support
#
# One way to use this is by placing it into a file called "cors_support"
# under your Nginx configuration directory and placing the following
# statement inside your location block(s):
#
#   include cors_support;
#
# A limitation to this method is that Nginx doesn't currently send headers
# specified by add_header when the backend returns a 4xx or 5xx status code.
#
# For more information on CORS, please see: http://enable-cors.org/
# Forked from this Gist: https://gist.github.com/michiel/1064640
#

set $cors '';
if ($http_origin ~* 'https?://(localhost|www\.yourdomain\.com|www\.yourotherdomain\.com)') {
        set $cors 'true';
}

if ($cors = 'true') {
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
}

if ($request_method = 'OPTIONS') {
        return 204;
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
29
Help us understand the problem. What are the problem?