我嘗試在 js 中的 fetch 承諾中獲取我自定義的 php 錯誤訊息。但看起來基本捕獲只給了我來自 http 回應代碼的狀態文本。
我的 php 是用 symfony 寫的
#[Route('/test', name:'test', methods: ['POST'])]
public function test(Request $req): Response
{
return new JsonResponse(['error' => 'my Cusom Error'], 400);
}
javascript:
let btn = document.getElementById('myButton');
btn.addEventListener('click', function(event){
const fd = new FormData(); // need it because want to send some files with it later
fd.append('user', 'myUserName');
fetch('/test', {method: 'POST', body: fd})
.then((response) => {
if(!response.ok){
throw Error(response.statusText);
// how to catch the message returned form the server here?
// the response object does not have this information
// using response.error() returns a error that error is not function
// response.error is undefined and has no information
// a workaround is using the resposen.json().then((errorData) => {...}) inside here, but looks not fine for me.
}
return response.json();
})
.then((data) => {
console.log('data received', data);
})
.catch((error) => {
console.log(error);
});
});
非常感謝@GoldenretriverYT。我的新 JS 看起來像這樣并且作業正常
fetch('/api-test', {method: 'POST', body: fd})
.then(async (response) => {
if (!response.ok) {
throw await response.json();
}
})
.then((data) => {
console.log('data received normal', data);
})
.catch((error) => {
console.error('error', error);
});
uj5u.com熱心網友回復:
你可以像往常一樣得到身體。
throw await response.json();
會正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355148.html
標籤:javascript php symfony 拿来
上一篇:使用其父項獲取子項的xpath
