2016-12-22 11 views
1

ajax jqueryを使用してデータをlaravel 5.3のWebサービスに送信したいとします。laravel 5.3からajax jqueryでWebサービスにデータを送信

$.ajax({ 
     type: "POST", 
     url: "http://199.166.212.50:8080/.../add", 
     contentType:'application/json', 
     data: { 
      "requester": 
      { 
       "userName": "jac", 
       "password": "111" 
      }, 
      "request": 
      { 
       "userName":userName, 
       "password":password, 
       "firstName": firstName, 
       "lastName": lastName, 
       "homeLocationLatLong": 
       { 
        "latitude": homeLocationLatLong_latitude, 
        "longitude": homeLocationLatLong_longitude 
       }, 
       "homeLocationText": homeLocationText, 
       "homePhoneNumber": homePhoneNumber, 
       "cellPhoneNumber": cellPhoneNumber 

      } 

     }, 
     dataType: "json", 
     success: function (result) { 
      console.log(result); 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      alert(xhr.status); 
      alert(thrownError); 
     } 
    }) 

が、私は、データを送信するとき、私はこのエラーを参照してください:私のAjaxのコードは、(この問題のURLは一例である)である

XMLHttpRequest cannot load http://199.166.212.50:8080/.../add. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. 

私は何をしなければなりませんか?

+1

可能な複製(http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain) –

答えて

1

私は同じ問題がありました。私はthis linkを使用し、Allow-Control-Allow-Origin: *をクロムブラウザに追加します。

1

ここでの問題は、エンドポイントURLがクロスソース要求に対してアクセスを許可しないことです。

私はクロスオリジン・リクエストを許可するようにLaravelエンドポイント上で、このコードを追加することをお勧めしたい:

header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); 
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With'); 
header('Access-Control-Allow-Credentials: true'); 

また、あなたはCSRFトークンなしでエンドポイントに投稿している場合は、LaravelのCSRF保護がスローされますエラー。私はトークンを含めることをお勧めします。これに関するより多くの情報はここにあります:https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token

+0

私はlaravelで新しいです。私はこのラインを追加しなければならないlaravel 5.3エンドポイントはどこですか? – narges

0

お試しくださいこれはあなたのために働くでしょう。 [jQueryのAJAXのクロスドメイン]の

<script> 
    $("#login_info").click(function(){ 
    var name = $('#username').val(); 
    var pass = $('#password').val(); 
    var token_key = $('input[name=_token]').val(); 
     $.ajax({ 
     type: "POST", 
     url: '{{url("admin_panel/login/auth")}}', 
     data: { 
     '_token': token_key, 
     'username': name, 
     'password': pass 
     }, 
     success: function(data) 
     { 
     alert('in_sucess'); 
     } 
    }) 
}); 

関連する問題