401未授权DELETE请求通过Ajax在laravel REST的API [英] 401 Unauthorized DELETE request to RESTful API in laravel via Ajax
问题描述
我已经创建了使用的 laravel 控制器一个REST的API。我有一个 PhotosController
具有毁灭($ ID)
方法资源删除。我也有一块的javascript code发送一个删除
请求我的应用程序。结果应该是删除的照片与的$ id
的id。但laravel不路由我的要求破坏
方法。相反,它发送的 401未授权错误。
I've created a restful API using laravel controllers. I have a PhotosController
which has a destroy($id)
method for resource deletion. also I have a piece of javascript code that sends a DELETE
request to my app. the result should be the deletion of the photo with $id
id. but laravel doesn't route my request to destroy
method. instead it sends an 401 Unauthorized error.
的事情是,我想送通过
要求我的应用程序不会让我的请求进行路由!阿贾克斯
,而 laravel删除
the thing is that I want to send DELETE
request to my app via Ajax
, but laravel doesn't let my request to be routed!
routes.php文件文件:
Route::resource('photos', 'PhotosController');
破坏方法:
public function destroy($id)
{
try{
unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
Session::forget('photo');
$msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
return Response::json(array('success' => $msg));
}catch (Exception $e){
App::abort(500, $e->getMessage());
}
}
我的Ajax请求:
$.ajax(
{
url: "/photos/" + name,
method : "DELETE", // Or POST : result is the same
data :{
_token : $("input[name=_token]").val(),
_method : 'DELETE'
},
success: function(data, textStatus, jqXHR ){
parent.replaceWith("");
toastr.success(data['success']);
$("#overlay").hide();
},
beforeSend : function(jqXHR, settings ){
$("#overlay").show();
},
error : function(jqXHR, textStatus, errorThrown ){
toastr.error(jqXHR.responseText);
$("#overlay").hide();
}
}
);
感谢您的帮助。
Thanks for your help.
推荐答案
我做这样的事情所有的时间在我的Laravel应用程序没有问题。这code允许用户通过AJAX删除资源,而$ P $第一psenting一个引导确认对话框。在code的布局顺序将发生的事件。
I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.
查看与资源,删除
<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
<i class="fa fa-trash fa-lg"></i>
</a>
jQuery来要求用户进行确认模态
$('.delete-plan').on('click', function(e) {
e.preventDefault();
var data = {
'route': $(this).attr('href'),
'redirect': $(this).data('redirect'),
'modal_title': 'Delete Plan',
'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
'lang': $(this).data('lang')
};
loadDestroyModal(data);
});
function loadDestroyModal(data) {
$.get('/ajax/destroy-modal', { data: data }, function(modal) {
$('body').append(modal);
$('#destroy-modal').modal('show');
});
}
Ajax控制器
// routed by /ajax/destroy-modal
public function destroyModal() {
$data = Input::get('data');
$params = [
'route' => $data['route'],
'redirect' => $data['redirect'],
'title' => $data['modal_title'],
'content' => $data['content_view'],
'lang' => $data['lang']
];
return View::make('_helpers.modal-destroy', $params);
}
消灭确认书模态(_helpers.modal灭)
<div id="destroy-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true"><i class="fa fa-times"></i></span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">{{ $title }}</h4>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
<button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
jQuery来PROCESS destroy方法和重定向闪烁信息
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
var redirect = $(this).data('redirect');
var lang = $(this).data('lang');
$(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');
$.ajax({
'url': $(this).data('route'),
'type': 'DELETE',
'success': function(response) {
if (response) {
redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
} else {
redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
}
}
});
});
PLANS控制器
public function destroy($id)
{
try
{
Stripe::plans()->destroy(['id' => $id]);
return Response::json(TRUE);
}
catch (Exception $e)
{
return Response::json(FALSE);
}
}
JQUERY重定向
function redirectWithFlashMessage(redirect, type, status, lang) {
var params = {
type: type,
status: status,
lang: lang
};
$.get('/ajax/flash', params, function(response) {
window.location.href = redirect;
});
}
Ajax控制器(转发与Flash)
public function flashData() {
$message_type = 'success' == Input::get('status') ? 'success' : 'failure';
$message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];
Session::flash($message_type, $message);
return ['status' => $message_type, 'message' => $message];
}
这是一个很大的code,但一旦安装它是非常容易复制。
It's a lot of code but once setup it's extremely easy to replicate.
这篇关于401未授权DELETE请求通过Ajax在laravel REST的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!