###問題点
ajaxでrailsのAPサーバーへポストするとエラーで返ってくる。
同じことをpostmanですると正常に返ってくる。
###エラーメッセージ
- ajaxでのポスト時、chromeのconsoleに表示される内容
OPTIONS https://api.************/users/login 401 () Failed to load https://api.************/users/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.33.10:3000' is therefore not allowed access. The response had HTTP status code 401.
###ajaxのコード
- postmanからrailsサーバーへポストしたコード(問題なく返ってきたもの)をコピペして利用。
変えた箇所は「fail」くらい。
※ちなみにcurlもコピペできて、叩いたら問題なくポストできて、意図したcookieも取得できた。
$('#button-login').on('click', function(){ var settings = { "async": true, "crossDomain": true, "url": "https://api.************/users/login", "method": "POST", "headers": { "content-type": "application/json", "cache-control": "no-cache", "postman-token": "6eaa639b-0379-f113-6596-**********" }, "processData": false, "data": "{'***********'}"; console.log(settings); $.ajax(settings) .done(function (result) { console.log(result); }) .fail(function(XMLHttpRequest, textStatus, errorThrown){ console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); alert('fail!'); }) });
###知りたいこと
- postmanからはなぜいけるのか。
- ajaxからはなぜいけないのか。仕様なのでしょうか。
- corsの設定は必要なのか。(今はしていない)
どなたか詳しい方、よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。