Laravel 5.5 ajax call 419(未知状态)

时间:2017-09-28 09:54:09

标签: php jquery ajax laravel

我做了一个ajax调用,但我一直收到这个错误:

  

419(未知状态)

不知道是什么原因导致我在其他帖子上看到它必须用csrf令牌做一些事情,但我没有表格,所以我不知道如何解决这个问题。

我的电话:

$('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");


      $.ajax({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });
  });

我的路线:

Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');

我的控制器方法

/**
 * Fetches a company
 *
 * @param $companyId
 *
 * @return array
 */
public function fetchCompany($companyId)
{
    $company = Company::where('id', $companyId)->first();

    return response()->json($company);
}

最终目标是在html元素中显示来自响应的内容。

20 个答案:

答案 0 :(得分:218)

在头部分使用:

<meta name="csrf-token" content="{{ csrf_token() }}">

并在ajax中获取csrf标记:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

请参阅Laravel文档csrf_token

答案 1 :(得分:20)

解决此问题的另一种方法是在ajax数据中使用_token字段,并在刀片中设置{{csrf_token()}}的值。这是我刚刚尝试过的工作代码。

$.ajax({
    type: "POST",
    url: '/your_url',
    data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
    success: function (data) {
       console.log(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);

    },
});

答案 2 :(得分:8)

这与Kannan的答案类似。但是,这解决了不应将令牌发送到跨域网站的问题。如果是本地请求,则仅设置标头。

HTML:

<meta name="csrf-token" content="{{ csrf_token() }}">

JS:

$.ajaxSetup({
    beforeSend: function(xhr, type) {
        if (!type.crossDomain) {
            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
        }
    },
});

答案 3 :(得分:7)

您的会话域可能与您的应用程序URL和/或用于访问该应用程序的主机不匹配。

1.)检查.env文件:

USE [BOB]
GO
/****** Object:  StoredProcedure [dbo].[usp_TrailGapReportDownload]    Script Date: 3/7/2018 10:25:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_TrailGapReportDownload]
(
   @ProductGroup NVARCHAR(200) = ''
  ,@Region NVARCHAR(100) = ''
  ,@State NVARCHAR(100) = ''
  ,@City NVARCHAR(100) = ''
  ,@BOMBucket bigint = NULL
  ,@Agency NVARCHAR(200) = ''
  ,@Agent NVARCHAR(200) = ''   
)
--exec usp_TrailGapReportDownload '','','','',NULL,'',''
--exec usp_TrailGapReportDownload '','BURDWAN REGION','','',0,'39e24168319ef3b2220c9c2394e35f50',''
-- exec usp_TrailGapReportDownload '','','','GANGTOK',0,'',''
--exec usp_TrailGapReportDownload '','','','ABOHAR',6,'',''
AS
BEGIN

DECLARE
        @sql NVARCHAR(MAX),  
        @paramlist  NVARCHAR(4000), 
        @nl CHAR(2) = CHAR(13) + CHAR(10)

SELECT @sql = '

            ;WITH trailsCTE AS(

                select *
                from 
                    (select 
                        Rn=row_number()over (partition by acc.AGREEMENTID order by (select 1))
                        ,f.DispositionCode
                        ,acc.BUCKET,acc.CURRENT_BUCKET
                        ,acc.AGREEMENTID as AccountNumber
                        ,acc.NPA_STAGEID AS NPAFlag
                        ,acc.PRODUCT
                        ,acc.ProductGroup
                        ,acc.BRANCH  as BRANCHAlpha
                        ,acc.ZONE as ZONE
                        ,acc.Region as REGION
                        ,acc.State  as State
                        ,acc.CITY as CITY 
                        ,acc.CUSTOMERNAME as [Account Owner]
                        ,(AccOwner.FirstName+'' ''+ AccOwner.LastName) as AllocationOwnerName
                        ,ds.Name as AllocationOwnerRole
                        ,AccOwner.CustomId as AllocationOwnerCode
                        ,TelAgency.FirstName as TeleCallingAgencyName
                        ,TelAgency.CustomId as TeleCallingAgencyCode
                        ,(telAgent.FirstName+'' ''+ telAgent.LastName) as TeleCallerName
                        ,telAgent.CustomId as TeleCallerCode
                        ,FieldAgency.FirstName as FiedAgencyName
                        ,FieldAgency.Id as FiedAgencyId
                        ,FieldAgency.CustomId as FiedAgencyCode
                        ,(FieldAgent.FirstName+'' ''+ FieldAgent.LastName) as FieldAgentName
                        ,FieldAgent.Id as FieldAgentId
                        ,FieldAgent.CustomId as FieldAgentCode
                        ,[Primary Allocation status for Tele-calling Agency] = iif(TelAgency.CustomId is null, ''GAP'',''Allocated'')
                        ,[Primary Allocation status for Field Agency]= iif(FieldAgency.CustomId is null, ''GAP'',''Allocated'')
                        ,[Secondary allocation Status for tele-Calling agent]=iif(telAgent.CustomId is null, ''GAP'',''Allocated'')
                        ,[Secondary allocation Status for field agent]=iif(FieldAgent.CustomId is null, ''GAP'',''Allocated'')
                        ,acc.CUSTOMERNAME
                        ,convert(date,(select top 1 CreatedDate from Collections WHERE Collections.AccountId=Acc.Id ORDER BY CreatedDate DESC)) AS LastPaymentDate
                        ,convert(date,(select top 1 PTPDate from Feedback f WHERE  f.AccountId=Acc.Id ORDER BY PTPDate DESC)) AS LastPTPDate
                        ,convert(date,(select top 1 DispositionDate from Feedback f WHERE f.AccountId=Acc.Id ORDER BY DispositionDate DESC)) AS LastDispositionDate
                        ,(select top 1 DispositionGroup from Feedback f WHERE f.AccountId=Acc.Id ORDER BY DispositionDate DESC) AS LastDispositionCodeGroup
                        ,(select top 1 DispositionCode from Feedback f WHERE f.AccountId=Acc.Id ORDER BY DispositionDate DESC) AS LastDispositionCode
                        --,convert(date,F.DispositionDate) AS LastDispositionDate
                        ,dbo.getDispositionCodeGroupFromDispostionCode(F.DispositionCode) AS [Current Disposition code group]
                        ,F.DispositionCode AS [Current Disposition code]
                        ,(Feedcollector.FirstName+'' ''+ Feedcollector.LastName) as CollectorName
                        ,Feedcollector.CustomId as CollectCode
                        ,RightPartyContact
                        ,PTPAmount 
                        ,convert(date,f.PTPDate) as PTPDate
                        ,AssignTo
                        ,AssignReason as ReasonForAssigning
                        ,IsReallocationRequest as ReallocationRequest
                        ,ReallocationRequestReason as ReallocationReason
                        ,NewArea as NewArea
                        ,NewAddress as NewAddress
                        ,f.State as NewState
                        ,f.City as NewCity
                        ,NewContactNo as NewContactNumber
                        ,NewEmailId as NewEmailID
                        ,f.Remarks 
                        ,NextAction
                        ,NonPaymentReason as ReasonForNonPayment
                        ,PickAddress as PickUpAddress
                        ,DispositionDate
                        ,[Trail Status]= iif((TelAgency.CustomId is null AND FieldAgency.CustomId is null AND telAgent.CustomId is null AND FieldAgent.CustomId is null),''NA'',
                                         iif(TelAgency.CustomId is not null OR FieldAgency.CustomId is not null OR telAgent.CustomId is not null OR FieldAgent.CustomId is not null
                                              and f.DispositionCode is null,''Gap'',''Trail Received'')) 
                        from LoanAccounts acc                    
                        left outer join Feedback F ON F.AccountId=acc.ID
                        left outer join ApplicationOrg TelAgency on TelAgency.id=acc.TeleCallingAgencyId
                        left outer join ApplicationUser telAgent on telAgent.id=acc.TeleCallerId
                        left outer join ApplicationOrg FieldAgency on FieldAgency.id=acc.AgencyId
                        left outer join ApplicationUser FieldAgent on FieldAgent.id=acc.CollectorId
                        left outer join ApplicationUser Feedcollector on Feedcollector.id=f.CollectorId
                        left outer join ApplicationUser AccOwner on AccOwner.id=acc.AllocationOwnerId
                        left outer join CompanyUserDesignation com on AccOwner.id=com.CompanyUserId
                        left outer join Designation ds on ds.id=com.DesignationId )x where x.Rn=1)

                    select                   
                    AccountNumber,NPAFlag,PRODUCT=dbo.getProductNameFromCode(PRODUCT),
                    [BOM Bucket]=t.BUCKET,[Current Bucket]=t.CURRENT_BUCKET,
                    BRANCHAlpha,ZONE,REGION,State,CITY,
                    [Account Owner],AllocationOwnerName,AllocationOwnerRole,AllocationOwnerCode,
                    TeleCallingAgencyName,TeleCallingAgencyCode,TeleCallerName,TeleCallerCode,
                    FiedAgencyName,FiedAgencyCode,FieldAgentName,FieldAgentCode,
                    [Primary Allocation status for Tele-calling Agency],[Primary Allocation status for Field Agency],
                    [Secondary allocation Status for tele-Calling agent],[Secondary allocation Status for field agent],
                    CUSTOMERNAME,LastPaymentDate,LastPTPDate,LastDispositionDate,
                    LastDispositionCodeGroup=dbo.getDispositionCodeGroupFromDispostionCode(LastDispositionCode),LastDispositionCode,
                    [Current Disposition code group],[Current Disposition code],
                    CollectorName,CollectCode,RightPartyContact,PTPAmount,PTPDate,AssignTo,ReasonForAssigning,
                    ReallocationRequest,ReallocationReason,NewArea,NewAddress,NewState,NewCity,NewContactNumber,NewEmailID,
                    Remarks,NextAction,ReasonForNonPayment,PickUpAddress,DispositionDate,[Trail Status]
                    from trailsCTE t WHERE 1=1 AND t.[FieldAgentId] IS NOT NULL '  + @nl

IF @ProductGroup != '' SELECT @sql += ' AND t.ProductGroup = @ProductGroup' + @nl
IF @Region != '' SELECT @sql += ' AND t.Region = @Region' + @nl
IF @State != '' SELECT @sql += ' AND t.STATE = @State' + @nl
IF @City != '' SELECT @sql += ' AND t.City = @City' + @nl
IF @BOMBucket IS NOT NULL SELECT @sql += ' AND t.BUCKET = @BOMBucket' + @nl
IF @Agency != '' SELECT @sql += ' AND t.[FiedAgencyId] = @Agency' + @nl
IF @Agent != '' SELECT @sql += ' AND t.[FieldAgentId] = @Agent' + @nl

print @sql

SELECT @paramlist = '
      @ProductGroup NVARCHAR(200)
      ,@Region NVARCHAR(100)
      ,@State NVARCHAR(100)
      ,@City NVARCHAR(100)
      ,@BOMBucket bigint
      ,@Agency NVARCHAR(200)
      ,@Agent NVARCHAR(200)    
     '
    EXEC sp_executesql 
       @sql
      ,@paramlist
      ,@ProductGroup     
      ,@Region
      ,@State
      ,@City
      ,@BOMBucket     
      ,@Agency
      ,@Agent 

END
GO


Table 'Feedback'. Scan count 1065818, logical reads 10626649, physical reads 9, read-ahead reads 20931, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'Collections'. Scan count 223, logical reads 1155, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'Designation'. Scan count 0, logical reads 237346, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'Worktable'. Scan count 118673, logical reads 237609, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'CompanyUserDesignation'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'ApplicationUser'. Scan count 637544, logical reads 1354626, physical reads 0, read-ahead reads 12, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'ApplicationOrg'. Scan count 0, logical reads 569626, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Table 'LoanAccounts'. Scan count 1, logical reads 4447447, physical reads 14120, read-ahead reads 79730, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

2.)检查config / session.php

验证值以确保它们是正确的。

答案 4 :(得分:5)

在您的页面中使用此

<meta name="csrf-token" content="{{ csrf_token() }}">

并且在你的ajax中将它用于数据:

_token: '{!! csrf_token() !!}',

即:

$.ajax({
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {
                   _token: '{!! csrf_token() !!}',
                 },
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });

感谢。

答案 5 :(得分:4)

在我的情况下,我忘了将csrf_token输入添加到提交的表单中。 所以我这样做了 HTML:

<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>

JS:

//setting containers
        var _token = $('input#_token').val();
        var l_img = $('input#l_img').val();
        var formData = new FormData();
        formData.append("_token", _token);
        formData.append("l_img", $('#l_img')[0].files[0]);

        if(!l_img) {
            //do error if no image uploaded
            return false;
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/my_url",
                contentType: false,
                processData: false,
                dataType: "json",
                data : formData,
                beforeSend: function()
                {
                    //do before send
                },
                success: function(data)
                {
                    //do success
                },
                error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
                {
                    if( jqXhr.status === "422" ) {
                        //do error
                    } else {
                        //do error
                    }
                }
            });
        }
        return false; //not to post the form physically

答案 6 :(得分:4)

如果您已经完成了上述建议并仍然遇到问题。

确保env变量:

SESSION_SECURE_COOKIE

设置为false ,如果您没有SSL证书,就像在本地一样。

答案 7 :(得分:3)

即使您有bytesTransferred = fileIChannel.transferTo(0, fileIChannel.size(), socketChannel); // or using a buffer ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024*8); while (fileIChannel.read(byteBuffer) != -1) { byteBuffer.flip(); bytesTransferred += socketChannel.write(byteBuffer); byteBuffer.clear(); ,如果您使用Laravel csrf_token验证您的控制器操作,您也可以获得419响应。在这种情况下,您应该在Policies课程中添加必要的政策功能。

答案 8 :(得分:2)

如果要从文件加载.js,则必须在&#34; main&#34;中使用csrf_token设置变量。 .blade.php文件,用于导入.js并在ajax调用中使用该变量。

index.blade.php

...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
        var token = '{{ csrf_token() }}';
</script>

anotherfile.js

$.ajax({
    url: 'yourUrl',
    type: 'POST',
    data: {
        '_token': token
    },
    dataType: "json",
    beforeSend:function(){
        //do stuff
    },
    success: function(data) {
        //do stuff
    },
    error: function(data) {
        //do stuff
    },
    complete: function(){
        //do stuff
    }
});

答案 9 :(得分:1)

我将SESSION_SECURE_COOKIE设置为true,因此我的开发环境在登录时无法正常工作,因此我添加了SESSION_SECURE_COOKIE=false 到我的dev .env文件,并且一切正常,我的错误是更改了session.php文件,而不是将变量添加到.env文件中。

答案 10 :(得分:1)

您必须获取csrf令牌。

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

出现相同问题后,只需添加此元标记< meta name="csrf-token" content="{{ csrf_token() }}" >

在此之后也出现错误,您可以检查Ajax错误。然后还要检查Ajax错误

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

答案 11 :(得分:1)

只需序列化表单数据即可解决问题。

data: $('#form_id').serialize(),

答案 12 :(得分:1)

一些refs =&gt;

...
<head>
    // CSRF for all ajax call
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
 ...
 ...
<script>
    // CSRF for all ajax call
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...

答案 13 :(得分:0)

如果您忘记在ajax提交请求(POST)中包含此错误,也会发生此错误, contentType:false, processData:false,

答案 14 :(得分:0)

这非常适合您不需要表格的情况。

$.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
        }
    });

答案 15 :(得分:0)

formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);

答案 16 :(得分:0)

即使我已经发送过csrf令牌,也遇到了此错误。原来服务器上没有剩余空间了。

答案 17 :(得分:0)

解决控制台上419个未知状态的一种简单方法是将该脚本放入FORM中。 {{csrf_field()}}

答案 18 :(得分:0)

2019 Laravel更新,从没想过我会发布此消息,但对于像我这样的开发人员,使用Laravel 5.8及更高版本上的浏览器获取API。您必须通过headers参数传递令牌。

var _token = "{{ csrf_token }}";
fetch("{{url('add/new/comment')}}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': _token,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(name, email, message, article_id)
            }).then(r => {
                return r.json();
            }).then(results => {}).catch(err => console.log(err));

答案 19 :(得分:0)

这对我有用:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
  }
});

在此之后设置常规的AJAX调用。示例:

    $.ajax({
       type:'POST',
       url:'custom_url',

       data:{name: "some name", password: "pass", email: "test@test.com"},

       success:function(response){

          // Log response
          console.log(response);

       }

    });