【问题标题】:Tell Laravels Validator where to look inside validation request array告诉 Laravel Validator 在哪里查看验证请求数组
【发布时间】:2020-02-23 17:43:49
【问题描述】:

如果我通过使用“数据”选项使用 axios 验证我的前端表单,它在我的后端 laravel 应用程序中的验证失败。

axios.post('http://example.com/', {
  'Content-Type': 'multipart/form-data',
  Accept: 'application/json',
  data: {
      email: 'email@email.com',
      password: '12345678',
    }
}).then(res => console.log(res))
  .catch(err => console.log(err));

所以这里我使用“数据”选项来验证。

$request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string'
]);

返回:422 email is required 需要密码。

这是请求的格式:

{Content-Type: "application/json", data: {email: "email@email.com", password: "12345678"}}

但是,如果我使用 axios 以这种方式提交表单,它会验证并且我已登录:

'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
'email': 'email@email.com',
'password': '12345678',

所以我的问题是如何告诉验证器查看数据对象的内部?

编辑 1: 按照要求dd($request->attributes);返回:

ParameterBag {#53
  #parameters: []
}

【问题讨论】:

    标签: javascript ajax laravel validation axios


    【解决方案1】:

    这是因为您在 axios 请求中将 headers 添加为 data。你的请求应该是这样的:

    const headers = {
        'Accept': "application/json",
        'Content-Type': "application/json",
    };
    
    let data: {
          email: 'email@email.com',
          password: '12345678',
        };
    
    axios.post('http://example.com/',data, {headers:headers})
                .then( (response) => {
                    //do the stuff
                })
                .catch( (error) => {
                    // do the stuff
                });
    

    Note: axios post 函数将第一个 argument 作为 url,第二个作为 data,第三个作为 config (headers etc),而在您的情况下,您将标题与数据混合。 你可以阅读更多关于axios here

    谢谢。

    【讨论】:

      【解决方案2】:

      问题是,为什么你需要在你的 axios 中添加data

      如果你添加data,那么你的验证应该是这样的:

      $request->validate([
          'data.email' => 'required|string|email',
          'data.password' => 'required|string',
      ]);
      

      【讨论】:

      • 返回未经授权。不知道为什么。
      • 当然,因为如果你用data包装axios发送的数据,你需要使用$request->get('data.email')来获取邮件,而不是$request->get('email')。顺便说一句,您将标题与数据混合在一起。为什么?您不需要用data 包装数据,只需axios.post('http://example.com/', {email: 'email@email.com', password: '12345678'})
      猜你喜欢
      • 2021-02-15
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 2016-08-10
      • 2020-06-28
      • 2020-09-11
      • 1970-01-01
      • 2017-11-21
      相关资源
      最近更新 更多