axios post 查明数据是否有效

发布于 2025-01-16 02:29:27 字数 1999 浏览 0 评论 0原文

好吧,我已经结束了一天的工作,但我的思考还不够清晰。这就是我所拥有的...

一个 Laravel 控制器,向它发送一个用户名,它会告诉我该用户名是否可用,如果不可用,它会给我一个 422 代码

public function checkUsername(Request $request) {
        Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:users'],
        ])->validate();
    
        return response()->json([
            'valid' => true,
            'data' => [
                'message' => 'Username is available!'
            ]
        ], 200);
    }

有效响应示例:

{"valid":true,"data":{"message":"Username is available!"}}%

要测试的curl是:

curl -X POST -H "Content-Type: application/json" -d '{"name": "bossryan"}' http://127.0.0.1:8000/api/checkusername

下一步:我有一个使用 Vee-validate 的前端 Vue。它做了很多事情,但我需要将这个最新的验证添加到组合中,所以如果用户名被采用(我没有从上面得到有效的响应,它需要回复“此用户名已被采用”

validateUsername(value) {
                // if the field is empty
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^[a-zA-Z0-9_.+-]{4,20}$/i;
                if (!regex.test(value)) {
                    return 'This must be a minimum of 4 characters';
                }
                return true;
            },

)是我创建的 axios,但它不起作用:

const isUnique = (value) => {
                    return axios.post('/api/checkusername', { email: value }).then((response) => {
                        // Notice that we return an object containing both a valid property and a data property.
                        return {
                        valid: response.data.valid,
                        data: {
                            message: response.data.message
                            }
                        };
                    });
                };

我知道我需要添加 axios,但我只是花了很长时间来设置它,我的思绪一直在寻找可以帮助我的人。插入上面的axios请求 //全部很好,所以我可以完成这个工作,

感谢社区的帮助!

OK I am at the end of my day and I am not thinking straight. So this is what I have...

a Laravel controller, send it a username, and it tells me if the username is available, and if it isnt, it gives me a 422 code

public function checkUsername(Request $request) {
        Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:users'],
        ])->validate();
    
        return response()->json([
            'valid' => true,
            'data' => [
                'message' => 'Username is available!'
            ]
        ], 200);
    }

Example of valid response:

{"valid":true,"data":{"message":"Username is available!"}}%

The curl to test is:

curl -X POST -H "Content-Type: application/json" -d '{"name": "bossryan"}' http://127.0.0.1:8000/api/checkusername

Next: I have a frontend Vue using Vee-validate. It does a bunch of things, but I need to add this latest validation into the mix, so if the username is taken (I don't get the valid response from above, it needs to reply with "This username is already taken"

validateUsername(value) {
                // if the field is empty
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^[a-zA-Z0-9_.+-]{4,20}$/i;
                if (!regex.test(value)) {
                    return 'This must be a minimum of 4 characters';
                }
                return true;
            },

This is the axios I created but it isnt working:

const isUnique = (value) => {
                    return axios.post('/api/checkusername', { email: value }).then((response) => {
                        // Notice that we return an object containing both a valid property and a data property.
                        return {
                        valid: response.data.valid,
                        data: {
                            message: response.data.message
                            }
                        };
                    });
                };

I know I need to add in axios, but I am just having a heck of a time setting it up and my mind keeps rushing around. I am just looking for someone who can just help me plug in the axios request above //All is good, so I can finish this up.

THANKS FOR THE HELP COMMUNITY!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心是晴朗的。 2025-01-23 02:29:28

Vee-validate 似乎想要一个异步验证的解决承诺。如果状态 >= 400,Axios 将拒绝承诺,因此您需要进行相应的处理。

假设验证失败时,响应正文匹配相同的 { valid, data: { message } } 格式,您需要类似以下内容

const isUnique = (name) => 
  axios.post("/api/checkusername", { name })
    .then(({ data }) => data)
    .catch(err => ({ // resolve with error details
      valid: err.response?.data?.valid ?? false,
      data: {
        // get the message from the response if it exists
        message: err.response?.data?.data?.message ?? "Validation failed"
      }
    }));

export default {
  methods: {
    async validateUsername(value) {
      // do your synchronous checks as per question

      const check = await isUnique(value);
      return check.valid || check.data.message;
    }
  }
}

这将提供通用消息“Validation failed” 如果 422 响应正文与预期不符。

Vee-validate seems to want a resolved promise for async validation. Axios will reject the promise if the status is >= 400 so you need to handle that accordingly.

Assuming when validation fails that the response body matches the same { valid, data: { message } } format, you'd want something like the following

const isUnique = (name) => 
  axios.post("/api/checkusername", { name })
    .then(({ data }) => data)
    .catch(err => ({ // resolve with error details
      valid: err.response?.data?.valid ?? false,
      data: {
        // get the message from the response if it exists
        message: err.response?.data?.data?.message ?? "Validation failed"
      }
    }));

export default {
  methods: {
    async validateUsername(value) {
      // do your synchronous checks as per question

      const check = await isUnique(value);
      return check.valid || check.data.message;
    }
  }
}

This will provide a generic message "Validation failed" if the 422 response body doesn't match expectations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文