vue.js axios POST에서 Laravel로 JSON을 입수하려면 어떻게 해야 합니까?
Laravel Backend의 Axios를 사용하여 vuex에서 JSON 데이터를 수신하는 데 문제가 있습니다.
이와 같은 vuex 스토어가 있는데 클릭 한 번으로 백엔드로 전송하고 싶습니다.
order: {
delivery_id: null,
user_id: null,
is_active: true,
bill: null,
name: null,
surname: null,
father_name: null,
phone: null,
payment_type: 'cash',
delay: null,
cashback_paid: null,
card: null,
payment_screenshot: null,
cart: null,
}
vue 컴포넌트에는 다음 방법이 있습니다.
sendOrder() {
let order = this.$store.state.order.order;
console.log(order)
axios
.post('/api/products', order, {
header: {
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
그리고 이것은 꽤 간단한 Laravel 컨트롤러입니다.
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
그러나 이 POST 요청을 하면 빈 데이터가 응답으로 수신됩니다.
또한 Postman에서 API를 확인해보니 정상적으로 동작하고 있습니다.요청을 전송한 후 F12 > Network >에서 요청을 찾아 Request Payload 소스 데이터를 복사합니다.그리고 Postman body(raw, json)에 붙여넣고, 이 데이터로 같은 URL(http://localhost:8000/api/orders)에 요청하면 예상대로 "cash"가 반환됩니다.그래서 vue.js 또는 axios 문제라고 판단했는데 어떻게 수정해야 할지 모르겠어요.감사해요!
업데이트 JSON.stringify 순서에서 Content-Type을 이미 삭제하려고 시도했지만 동일한 결과, 즉 응답 데이터가 비어 있습니다.
Axi에서 순서를 사용하기 전에 JSON 데이터를 문자열화해야 합니다.
let order = JSON.stringify(this.$store.state.order.order);
몇 가지 코멘트 후 답변의 두 번째 부분:
루트 파일이 확실합니까?web.php 파일(같은 폴더)에서 mytest 등의 선언된 함수를 사용하여 컨트롤러를 호출합니다.
Route::post('/api/products', 'ProductController@mytest');
컨트롤러 로직을 이 함수에 넣습니다.
public function mytest()
{
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
}
(JSON.stringify와 조합하여) 동작하지 않는 경우는, 당신의 「매우 심플한 Laravel 컨트롤러」에 오타가 있는 것 뿐입니다.
언급URL : https://stackoverflow.com/questions/66719747/how-to-get-json-in-laravel-from-vue-js-axios-post
'programing' 카테고리의 다른 글
| Jackson & message - Json Mapping Exception - START_ARray 토큰이 아닌 것으로 역직렬화할 수 없음 (0) | 2022.09.25 |
|---|---|
| Java에서 목록으로 맵을 변환하는 방법 (0) | 2022.08.31 |
| DESTDIR 및 제조원 접두사 (0) | 2022.08.31 |
| Java로 플러그인 시스템을 구축하는 가장 좋은 방법 (0) | 2022.08.31 |
| C 프리프로세서는 왜 "linux"라는 단어를 상수 "1"로 해석합니까? (0) | 2022.08.31 |