【问题标题】:Can't check if request is ajax with $request->ajax() and Laravel 5.4无法使用 $request->ajax() 和 Laravel 5.4 检查请求是否为 ajax
【发布时间】:2018-10-18 22:45:59
【问题描述】:

我在尝试检查请求是否为 ajax 时遇到问题。这是我的代码:

路线

Route::post('cookies-alert', 'CookiesController@weUseCookies')->name('cookies.weuse');

控制器

namespace app\Http\Controllers;

use Illuminate\Http\Request;

class CookiesController extends Controller
{
    public function weUseCookies(Request $request)
    {
        if($request->ajax()){
          return response()->json(['status' => 'successful']);
        }else{
          return response()->json(['status' => 'error']);
        }
    }
}

表单(使用 Laravel 集合,它会自动创建 _token)

{{ Form::open(['route' => ['cookies.weuse', ''], 'method' => 'POST', 'id' => 'cookie-form']) }}
    ....
    <button type="submit">Ok</button>
{{ Form::close() }}

还有js

  $('#cookie-form').on('submit', function(e){
      e.preventDefault();
      // .....
      $.ajax({
        url: url,
        method: 'POST',
        dataType: 'JSON',
        data: data
      }).done( function (response) {
        var res = response;

        if( res.status == 'successful' ){
          console.log(res.status);
        }else{
          showError('error :(');
        }
      });
  });

我尝试过这种方式

$.ajax({
      url: url,
      type: 'POST',
      data: data,
      dataType: 'JSON',
      success: function (data) {
          console.log(data);
      }
  });

并使用来自 https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js 的 jquery 3.2.1

但它总是从我的控制器返回“错误”。

我也尝试像this 一样使用 Request::ajax(),但它会跳过 if{} 并从我的控制器转到 else{} 选项。

我做错了什么?

我的代码可以在本地运行,但不能在服务器上运行

【问题讨论】:

  • 记得将 CSRF 令牌添加到您的表单中。 {{ csrf_field() }}如果你没有设置meta标签,那就是。
  • 它已经添加到我的表单中

标签: php json ajax laravel response


【解决方案1】:

laravel 使用 X-Requested-With http 标头来检查传入的请求是否是 ajax,您还必须在表单中添加 @csrf 字段:

$.ajax({
  url: url,
  type: 'POST',
  // add _token field for csrf protection
  data: {
    _token : ''
  },
  dataType: 'JSON',
  // add x-forwarded-with also add X-CSRF-TOKEN header for csrf protection 
  headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-TOKEN': ..,
  }
});

或者你可以使用axios,因为 laravel 可以更好地使用它:

axios({
    method: 'POST',
    url: 'url',
    data: {
      _token: 'token',
   },
   responseType: 'json',
   headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-TOKEN': 'token,
   }
}

【讨论】:

  • 没有正常工作 $.ajax ,'我稍后会尝试 axios。但我注意到控制器正在接收数据。 csrf_field() 在我的表单中。如果我在 if($request->ajax()) 之前添加 return response()->json($request) ,则数据就在那里(csrf_field 和其他字段)并获得状态 200。我现在将尝试使用 axios。
  • Axios 没有工作 :( 。它发送数据,控制器接收它,我可以看到数据并使用它,但是行 if($request->ajax() ){...} 被“跳跃”了。Laravel 可能是问题吗?我可以决定不使用该行,但现在我想知道为什么 ->ajax() 不起作用。
【解决方案2】:

Request::wantsJson() 它也适用于 axios。

【讨论】:

    【解决方案3】:

    你需要在 app.js 中设置如下标题

    window.axios = require('axios');
    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    
    let token = document.head.querySelector('meta[name="csrf-token"]');
    
    if (token) {
      window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    } else {
      console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
    }
    
    window.Vue = require('vue');
    

    【讨论】:

      【解决方案4】:

      $request-&gt;wantsJson() 在 laravel 8 上与 axios 配合得很好。

      【讨论】:

        猜你喜欢
        • 2015-05-27
        • 2018-06-12
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 2019-07-23
        • 1970-01-01
        • 2017-09-13
        相关资源
        最近更新 更多