Laravel 8 Jetstream Inertia 所有 Inertia 请求都必须收到有效的 Inertia 响应

Laravel 8 Jetstream Inertia All Inertia requests must receive a valid Inertia response

我一直在努力为我的问题找到正确的答案我知道这个问题在 之前已经被问过,实际上还有很多其他地方,但是我找不到适合我的问题的答案。

vue组件

FooterNewsletter.vue

<template>
    <div class="lg:w-2/4 md:w-1/2 w-full px-8 border-l-2">
        <p class="font-bold text-3xl">
            Don't want to miss the latest cryptocurrency news?
        </p>
        <p class="py-3 text-lg">
            Get the latest news and updates by subscribing to our free
            newsletter 
        </p>
        <form @submit.prevent="subscribeToNewsletter">
            <div class="flex flex-col">
                <div class="flex">
                    <input
                        v-model="form.email"
                        type="text"
                        name="post_title"
                        class="
                            border-primary
                            focus:border-primary
                            focus:ring-offset-transparent
                            focus:ring-transparent
                        "
                        id="exampleFormControlInput1"
                        placeholder="Your E-mail"
                    />
                    <input
                        type="submit"
                        value="Subscribe"
                        :disabled="form.processing"
                        class="px-5 py-2 bg-primary text-white cursor-pointer"
                    />
                </div>
            </div>
        </form>
    </div>
</template>

<script>

export default {
    props: [],
    components: {

    },
    data() {
        return {
            form: this.$inertia.form({
                email: "",
            }),
        };
    },
    methods: {
        subscribeToNewsletter() {
            this.form
                .transform((data) => ({
                    ...data,
                    // remember: this.form.remember ? "on" : "",
                }))
                .post(this.route("newsletter.store"), {
                    onSuccess: (data) => {
                        console.log("data", data);
                    },
                    onError: (data) => {
                        console.log("data", data);
                    },
                });
        },
    },
};
</script>

控制器

NewsletterController.php

namespace App\Http\Controllers;

use App\Http\Requests\NewsletterStoreRequest;
use App\Models\Newsletter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

class NewsletterController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(NewsletterStoreRequest $request)
    {
        return response()->json([
            'message' => 'suss',
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

请求文件

NewsletterStoreRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class NewsletterStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => ['required', 'max:150', 'email'],
        ];
    }
}

路线

web.php

Route::post('/newsletter', [
    NewsletterController::class,
    'store',
])->name('newsletter.store');

在上面的示例中,我 return 一个 json 对象,它不被接受并给我这个错误

我已经尝试按照有关响应的惯性文档here我认为正确的答案应该在那里找到,我自己无法解决

我也查看了惯性 Jetstream 文档,但没有任何运气 here

我不想 return 一个新视图,我实际上希望它作为一个 ajax 请求工作重新加载页面或类似的东西。

我看到很多人都有这个问题,有谁知道出了什么问题以及我必须在控制器中 return 做什么?

对我来说,我不得不将控制器更改为:

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Models\Newsletter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests\NewsletterStoreRequest;

class NewsletterController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(NewsletterStoreRequest $request)
    {
        Newsletter::create([
            'email' => $request->email
        ]);

        return back()->with('flash', [
            'message' => 'success',
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

这里需要注意的是这部分:

    return back()->with('flash', [
        'message' => 'success',
    ]);

我在一个朋友的帮助下找到了解决我的问题的示例:vendor/laravel/jetstream/src/Http/Controllers/Inertia/ApiTokenController.php

这里他们 return 像我上面的例子一样带有 flash 消息,消息键将在 props->components->flash->message

它不会像我想的那样工作 ajax,因为它使用 Vue 路由,所以页面将在提交时重新加载。

我希望有人会觉得这有用。

此外,如果您因为在 vue 组件中使用数据而收到控制台错误,则必须检查包装器以检查数据是否为 ​​null,如下所示:

<ul
   v-if="assets != null"
   class="
   marketcap-rows
   border-l border-r border-gray-200
   flex flex-col
   "
   >
   <li
      v-for="asset in $props.assets.data"
      v-bind:key="asset"
      class="
      bg-white
      grid
      gap-4
      border-t border-gray-200
      "
      >
   </li>
</ul>

这就是我所说的支票:v-if="assets != null"

这是访问 jetstream 初始默认闪现消息的方法:

session()->flash('flash',  [
    'bannerStyle'=> 'danger',
    'banner' => 'this is the first message',
]);
return Inertia::render('Admin/Overview', [
    'users'
]);

您需要将其添加到您的渲染中...

文档:https://inertiajs.com/shared-data#flash-messages

class HandleInertiaRequests extends Middleware
    {
        public function share(Request $request)
        {
            return array_merge(parent::share($request), [
                'flash' => [
                    'message' => fn () => $request->session()->get('message')
                ],
            ]);
        }
    }