[英]Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request?
[英]Can't check if request is ajax with $request->ajax() and Laravel 5.4
我在尝试检查请求是否为 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
但它总是从我的控制器返回“错误”。
我也尝试像这样使用Request::ajax()但它跳过 if{} 并从我的控制器转到 else{} 选项。
我究竟做错了什么?
我的代码适用于本地但不适用于服务器
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,
}
}
Request::wantsJson()
它也适用于 axios。
你需要在 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');
Request::wantsJson()
它与 axios 一起工作,对我来说
$request->wantsJson()
与 laravel 8 上的 axios 配合良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.