laravel5.8请求失败,状态码为500

时间:2019-07-16 08:18:47

标签: php laravel axios laravel-5.8

我正在尝试使用axios laravel创建搜索栏,以按标题和描述进行需要,但我遇到此错误

Error: "Request failed with status code 500"
    createError http://127.0.0.1:8000/js/app.js:633
    settle http://127.0.0.1:8000/js/app.js:796
    handleLoad http://127.0.0.1:8000/js/app.js:166

我不知道问题出在哪里,

app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Mokoch</title>



    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}" >
                    <img src="{{ asset('svg/logo.png') }}" width="25%"  >
                    <span class="ml-">Mokoch</span>
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                  <!--   <ul class="navbar-nav mr-auto">
                        <li class="nav-item">
                            <a href="{{ route('posts.index') }}" class="nav-link">Voir les offres</a>
                        </li>
                    </ul> -->

                <form method="POST" action="{{ route('post.search') }}" onsubmit="search(event)" id="searchForm">
                    @csrf
                    <div class="form-group">
                        <input type="text" name="form-control" id="words">
                        <button type="submit" class="btn btn-primary">Rechercher</button>
                    </div>
                </form>
                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                            </li>
                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->nom }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">

                                    <a href="{{ route('posts.create') }}" class="dropdown-item">Mettre une annonce</a>

                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
        <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    @yield('extra-js')

</body>
</html>

welcome.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
        <div class="row justify-content-center">
        <div class="col-md-8">

    @foreach ($posts as $post)
    <div class="card" style="width: 18rem;">

       <a href="{{ route('posts.show', ['post' => $post->id]) }}"> <img src="{{ asset('storage') . '/' . $post->image }}" class="w-100"></a>
      <div class="card-body">
        <h5 class="card-title">{{ $post->title }}</h5>
        <small>{{ Carbon\Carbon::parse($post->created_at)->diffForHumans() }}</small>
        <p class="card-text">{{ $post->descriptionpost }}</p>
        <p class="card-text">{{ $post->price }}</p>
        <a href="#" class="btn btn-primary">Voir</a>
    </div>
</div>
@endforeach

</div>
</div>
</div>
@endsection
    @section('extra-js')
    <script>
        function search(event)
        {
            event.preventDefault()
            const words = document.querySelector('#words').value
            const url = document.querySelector('#searchForm').getAttribute('action')
            axios.post(`${url}`, {
                words : words,
              })
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });
        }
    </script>
    @endsection

PostController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\Poststore;
use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $posts = DB::table('posts')->orderBy('created_at', 'DESC')->paginate(1000);

        return view('welcome',['posts'=> $posts]);
    }

    public function create()
    {
        return view('posts.create');
    }

    public function store()
    {
        $data = request()->validate([
            'title' => ['required', 'string'],
            'image' => ['required', 'image'],
            'price' => ['required', 'integer'],
            'descriptionpost' => ['required', 'string']
        ]);

        $imagePath = request('image')->store('uploads', 'public');

        $image = Image::make(public_path("/storage/{$imagePath}"))->fit(1200, 1200);
        $image->save();


        auth()->user()->posts()->create([
            'title' => $data['title'],
            'descriptionpost' => $data['descriptionpost'],
            'price' => $data['price'],
            'image' => $imagePath
        ]);

        return redirect()->route('profile.show', ['user' => auth()->user() ]);
    }

    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }

    public function search(Request $request)
    {
        $words = $request->words;
        $posts = DB::table('posts')->where('title', 'LIKE', '%$words%')->orWhere('descriptionpost', 'LIKE', '%$words%')->orderBy('created_at', 'DESC')->get();

        return response()->json(['success' => true, 'posts' => $post]);
    }
}

有人知道问题出在哪里?我该怎么做才能离开此错误,因为搜索栏不起作用:/?

1 个答案:

答案 0 :(得分:0)

在axios标头中使用csrf令牌: 下面的示例代码:

const words = document.querySelector('#words').value
const url = document.querySelector('#searchForm').getAttribute('action')
const data = JSON.stringify({
            words: words
        })
axios.post(`${url}`, data, {
                headers: { 
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': token.content 
                }
            }).then(
                response => console.log(response.data)
            ).catch(
                error => console.log(error)
            )