我收到此错误“从来源'http://localhost/api/auth/register'对来自'http://127.0.0.1:8000'的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否' access-control-allow-origin'标头出现在所请求的资源上。“
<template>
<div class="container mt-2">
<form autocomplete="off" @submit.prevent="register" method="post">
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.email }">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control bg-light border-0 small" placeholder="user@example.com" v-model="email">
<span class="help-block" v-if="has_error && errors.email">{{ errors.email }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password">Password</label>
<input type="password" id="password" class="form-control bg-light border-0 small" v-model="password">
<span class="help-block" v-if="has_error && errors.password">{{ errors.password }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password_confirmation">Conform Password</label>
<input type="password" id="password_confirmation" class="form-control bg-light border-0 small" v-model="password_confirmation">
</div>
<div class="alert alert-danger" v-if="has_error && !success">
<p v-if="error == 'registration_validation_error'">Validation error</p>
<p v-else>Please fill all the fields to get registered</p>
</div>
<input type="hidden" name="_token" :value="csrf">
<div class="text-center pb-3">
<button type="submit" class="btn btn-success btn-sm" style="background-color:#00A7F5;border:none;">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
email: '',password: '',password_confirmation: '',csrf: document.querySelector('meta[name="csrf-token"]').getattribute('content'),has_error: false,error: '',errors: {},success: false
}
},methods: {
register() {
var app = this
this.$auth.register({
data: {
email: app.email,password: app.password,password_confirmation: app.password_confirmation
},success: function () {
app.success = true
},error: function (res) {
app.has_error = true
app.error = res.response.error
app.errors = res.response.errors || {}
}
})
}
}
}
</script>
如果失败,则来自控制器的响应
$a = Validator::make($request->all(),[
'email' => 'required|email|unique:users','password' => 'required|min:6|confirmed',]);
if ($a->fails())
{
return response()->json([
'status' => 'error','errors' => $a->errors()
],422);
}
如果一切正常,那么
return response()->json(['status' => 'success'],200);
请让我知道这有什么问题,还有没有更好的方法来处理错误。请分享链接,我无法正确处理错误。 感谢所有帮助。