使用 ajax jquery 将数据从 laravel 5.3 发送到 Web 服务

Send data from laravel 5.3 to web service with ajax jquery

我想用 ajax jquery 将数据发送到 laravel 5.3 中的 Web 服务。我的 ajax 代码是(URL in this question is an example):

 $.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.

我必须做什么?

这里的问题是端点 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

我有同样的问题。我使用 this link 并将 Allow-Control-Allow-Origin: * 添加到 chrome 浏览器。

像这样尝试它会为你工作。

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