【问题标题】:Nuxt.js and Laravel Api - 422 Displaying Error instead of FormsNuxt.js 和 Laravel Api - 422 显示错误而不是表单
【发布时间】:2019-09-07 09:14:44
【问题描述】:

[错误][1]

大家好,

每当我收到来自 laravel 的错误返回时,nuxt.js 项目都会在页面上而不是 HTML/Forms 上显示错误。我该如何处理。 这是我的php代码


return response()->json([
                'errors' => [
                    'email' => ['Sorry we cant find you with those details.'],
                ],
            ], 422);

Javascript

 async submit() {
                await this.$auth.loginWith("local", {
                    data: this.form
                })

【问题讨论】:

    标签: laravel nuxt.js


    【解决方案1】:

    在您的 JavaScript 中,您需要将您的 await 承诺包装在 try catch 块中。这是您的 JS 的修复方法。

    try {
    
      await this.$auth.loginWith("local", {
        data: this.form
      })
    
    } catch (e) {
    
      return;
    }
    

    【讨论】:

    • 你真的能粘贴完整的代码吗?我自己正在尝试这个,它似乎不起作用。 ``` 方法: { async onSubmit() { await this.$auth .loginWith("local", { data: this.form }) .then(data => { this.$router.push("/dashboard") ; }) .catch(错误 => {}); } },```
    【解决方案2】:

    在这一点上这是一个老问题,但我想我会发布完整的代码,因为我很困惑并且没有找到很多好的答案:

    async handleSubmit() {
        try {
            const authResponse = await this.$auth.loginWith('local', { 
                data: this.formData
            });
            const { status, data } = authResponse;
    
            if (status === 200) 
                this.createFlashAlert({ 'success': 'Login successful' });
        } catch (error) {
            if (error.response.status === 422)
                this.createFlashAlert(error.response.data);
        }
    }
    

    所以清单:

    1. 如果您使用异步等待语法,请将登录调用包装在 try/catch 中(确保将其设为异步函数,即 async handleSubmit
    2. 在catch块中,使用error.response对象,这是axios的东西。有了这个,您将能够访问响应 statusdata

    如果您只记录 error 对象,那么您可以访问该错误中的响应并不明显,这让我很困惑。

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2015-01-07
      • 2020-02-15
      • 2018-09-09
      • 2020-05-01
      • 2023-01-21
      • 2017-11-07
      • 2013-01-22
      • 2020-09-19
      相关资源
      最近更新 更多