2016-12-22 246 views
1

我想用ajax jquery將數據發送到laravel 5.3中的Web服務。我的Ajax代碼是(URL在這個問題就是一個例子):將數據從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); 
     } 
    }) 

但是當我發送數據時,我看到這個錯誤:

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

[jQuery的AJAX跨域]的可能的複製(http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain) –

回答

1

我有同樣的問題。我使用this link並將Allow-Control-Allow-Origin: *添加到Chrome瀏覽器。

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

試試像這樣它會適合你。

<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'); 
     } 
    }) 
}); 

相關問題