我构建了 Laravel-API,通过 axios 和 VUE 3 与前端通信
这是我的 laravel TransactionController :
public function store(TransactionRequest $request)
{
try {
$transaction = Transaction::create($request->all());
return response()->json([
'message' => 'Transaction created.',
'data' => $transaction
], Response::HTTP_OK);
} catch (QueryException $e) {
return response()->json([
'message' => $e->errorInfo
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
我正在使用来自 FormRequest 的自定义验证:
public function rules()
{
return [
'title' => 'required',
'amount' => ['required', 'numeric'],
'type' => ['required', 'in:expense,revenue']
];
}
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$response = new JsonResponse([
'message' => 'The given data is invalid',
'errors' => $validator->errors()
], 422);
throw new \Illuminate\Validation\ValidationException($validator, $response);
}
这是我的 Create.vue :
<script>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
export default {
setup() {
const transaction = reactive({
title: '',
amount: '',
time: '',
type: ''
});
const validation = ref([]);
const router = useRouter();
function store() {
axios.post('http://127.0.0.1:8000/api/transaction', transaction)
.then(() => {
router.push({
name: 'transaction.index'
});
}).catch((err) => {
validation.value = err.response.data
console.log(validation)
});
}
return {
transaction,
validation,
router,
store
}
}
}
</script>
我使用 post man 尝试了我的 API,结果如下:
{
"message": "The given data is invalid",
"errors": {
"title": [
"The title field is required."
],
"amount": [
"The amount field is required."
],
"type": [
"The type field is required."
]
}
}
按预期工作
但是当我尝试在浏览器中控制台登录时,结果很复杂,比如嵌套对象和数组,请看图片
如何访问“数据”属性或如何使其像邮递员的结果一样简单?
答案 0 :(得分:0)
在您的函数中添加 .errors,这将返回来自后端的所有错误,如下所示。如果我理解你的问题
function store() {
axios.post('http://127.0.0.1:8000/api/transaction', transaction)
.then(() => {
router.push({
name: 'transaction.index'
});
}).catch((err) => {
validation.value = err.response.data.errors // added .errors
console.log(validation)
});
}