[英]API: Ajax post in Laravel - 403 (Forbidden)
I'm getting 403 forbidden
during ajax call.我在 ajax 通话期间收到
403 forbidden
。 This is happen only if the ajax
is on app.js
.仅当
ajax
在app.js
上时才会发生这种情况。 If I remove
from app.js
and put to index.blade.php
, is working perfectly.如果我从
app.js
remove
并放入index.blade.php
,则工作正常。
How can I make it working also on my app.js
?我怎样才能让它在我的
app.js
上也能工作? I've searched a lot, and found I needed to add this我搜索了很多,发现我需要添加这个
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
before the ajax, but is still not working..在 ajax 之前,但仍然无法正常工作..
controller: controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class API extends Controller
{
public function getSomething(Request $r)
{
$r->validate([
'user' => 'required'
]);
$data = DB::table('posts')->orderBy('id', 'desc')->get();
return $data;
}
}
web.php web.php
Route::group(['prefix' => 'api'], function(){
Route::post('getSomething', 'API@getSomething');
});
index.blade.php索引.刀片.php
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
.... some of my content ....
<script src="{{ asset('assets/js/app.js') }}"></script>
app.js应用程序.js
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url("api/getSomething") }}',
type: 'POST',
data: {
user: '1',
_token: '{{ csrf_token() }}',
_testThisAjax: true
},
success: function (c) {
console.log(c);
},
error: function(e)
{
console.log(e);
}
});
Since {{ url() }}
helper method will not work in app.js
file so you have to set url
in ajax由于
{{ url() }}
辅助方法在app.js
文件中不起作用,因此您必须在 ajax 中设置url
Your ajax should be like this if you put this in app.js
如果你把它放在
app.js
中,你的 ajax 应该是这样的
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/api/getSomething',
type: "POST",
data: {
user: '1',
_testThisAjax: true
},
success: function (c) {
console.log(c);
},
error: function(e)
{
console.log(e);
}
});
Note: use either ajax headers for csrf or in data like this:注意:将 ajax 标头用于 csrf 或在这样的数据中使用:
data: {_token: $('meta[name="csrf-token"]').attr('content') , 'key' : 'value'}
FOR MORE: https://laravel.com/docs/8.x/csrf更多信息: https://laravel.com/docs/8.x/csrf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.