axios发帖查看数据是否有效



好吧,我一天都快结束了,我没有思考清楚。所以这就是我所拥有的。。。

一个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 -X POST -H "Content-Type: application/json" -d '{"name": "bossryan"}' http://127.0.0.1:8000/api/checkusername

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

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请求的人//一切都很好,所以我可以完成这件事。

感谢社区的帮助!

Vee-validate似乎想要一个已解决的异步验证承诺。如果状态为>=,Axios将拒绝承诺400,所以你需要相应地处理。

假设验证失败时,响应主体匹配相同的{ 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;
}
}
}

这将提供一个通用消息"em";验证失败"如果422响应体与预期不匹配。

最新更新