У меня проблема с отправкой запроса на публикацию в моем проекте, например, всякий раз, когда я пытаюсь сделать запрос с помощью кнопки в своем приложении, у меня возникает ошибка с tp://localhost/delete-comment 404 (Not Found) send @
Это мой код, в котором я делаю запрос:
<script>
$(document).ready(function(){
// CSRF Token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name = "csrf-token"]').attr('content')
}
});
$(document).on('click', '.deleteComment', function () {
if (confirm('Are you sure you want to delete this comment?'))
{
var thisClicked = $(this);
var comment_id = thisClicked.val();
$.ajax({
type:'POST',
url: '/delete-comment',
data: {
'comment_id': comment_id,
'_token': $('meta[name = "csrf-token"]').attr('content')
},
success:function(res){
if (res.status == 200){
thisClicked.closest('.comment-container').remove();
alert(res.message);
}
else{
alert(res.message);
}
}
});
}
});
});
</script>
И это мой файл web.php:
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/', [App\Http\Controllers\Frontend\FrontendController::class, 'index']);
Route::get('tutorial/{category_slug}', [App\Http\Controllers\Frontend\FrontendController::class, 'viewCategoryPost']);
Route::get('/tutorial/{category_slug}/{post_slug}', [App\Http\Controllers\Frontend\FrontendController::class, 'viewPost']);
// Comment System
Route::post('comments', [App\Http\Controllers\Frontend\CommentController::class, 'store']);
Route::post('delete-comment', [App\Http\Controllers\Frontend\CommentController::class, 'destroy']); //here is the request i am getting
и ниже мой файл commentController.php, который имеет функцию уничтожения:
<?php
namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Comment;
use Illuminate\Support\Facades\Validator;
class CommentController extends Controller
{
public function store(Request $request)
{
if (Auth::check()) {
$validator = Validator::make($request->all(), [
'comment_body' => 'required|string'
]);
if ($validator->fails()) {
return redirect()->back()->with('message', 'Comment Area is Mandetory');
}
$post = Post::where('slug', $request->post_slug)->where('status', '0')->first();
if ($post) {
Comment::create([
'post_id' => $post->id,
'user_id' => Auth::user()->id,
'comment_body' => $request->comment_body,
]);
return redirect()->back()->with('message', 'Commented Successfully');
} else {
return redirect()->back()->with('message', 'No Such Post Found!');
}
} else {
return redirect('login')->with('message', 'Login first to comment');
}
}
public function destroy(Request $request) //here is the destroy function
{
if (Auth::check()) {
$comment = Comment::where('id', $request->comment_id)->where('user_id', Auth::user()->id)->first();
if ($comment) {
$comment->delete();
return response()->json([
'status' => 200,
'message' => 'Comment Deleted Successfully',
]);
} else {
return response()->json([
'status' => 500,
'message' => 'Something Went Wrong',
]);
}
} else {
return response()->json([
'status' => 401,
'message' => 'Login to Delete this Comment'
]);
}
}
}
Да и другие маршруты работают нормально.
Беги php artisan optimize или php artisan route:clear
Все еще с той же ошибкой.
Что у вас в адресной строке?
http://localhost/laravel_blog/tutorial/html/laravel Вы об этом спрашиваете?
Что у тебя APP_URL в .env?
Таким образом, ваш фактический URL-адрес, который вам понадобится для получения, вероятно, будет /laravel_blog/tutorial/html/laravel/delete-comment, каким бы ни был URL-адрес, чтобы увидеть только главную страницу вашего проекта laravel.
APP_URL=локальный хост
APP_URL в .env не имеет значения; который используется только для создания URL-адреса через взаимодействие с консолью. Как вы запускаете свое приложение Laravel? php artisan serve? Или через веб-сервер (LAMP, WAMP и т. д.)? Не имеет большого смысла то, что url: '/delete-comment' будет генерировать URL tp://localhost/delete-comment...
Я запускаю свое приложение через XAMPP
Так что ответ на мой вопрос был да, а не нет; ваше приложение находится в папке с именем laravel_blog.
да, мое приложение находится в папке Laravel_blog.






Чтобы убедиться, что вы указали правильный URL-адрес в ajax. Сначала назовите свой маршрут:
Route::post('delete-comment', [App\Http\Controllers\Frontend\CommentController::class, 'destroy'])->name('deleteComment');
Затем:
$.ajax({
type:'POST',
url: '{{route('deleteComment')}}',
Вау, теперь работает нормально! Большое спасибо за ваши усилия в решении проблемы. Ваша быстрая и эффективная работа сэкономила нам много времени и нервов.
я так рада это слышать
Я предлагаю использовать метод {{ route ('') }} для вызова маршрута.
В ваших маршрутах обязательно укажите название маршрута
Route::post('delete-comment', [App\Http\Controllers\Frontend\CommentController::class, 'destroy'])->name('delete-comment');
затем вызовите это в своем ajax
$.ajax({
type:'POST',
url: '{{ route('delete-comment') }}',
data: {
'comment_id': comment_id,
'_token': $('meta[name = "csrf-token"]').attr('content')
},
success:function(res){
if (res.status == 200){
thisClicked.closest('.comment-container').remove();
alert(res.message);
}
else{
alert(res.message);
}
}
});
Как вы размещаете свой сайт? Другие маршруты работают? У вас есть папка в вашем URL, например
http://localhost/public/?