javascript - 如何使用 fetch 在 javascript 中获取 php 错误消息
问题描述
我尝试在 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);
});
});
解决方案
你可以像往常一样得到身体。
throw await response.json();
将正常工作。
推荐阅读
- python - Conda 未安装最新版本
- c - 解析来自套接字的单个消息,其中包含 C 中的 2 个字符串
- angular6 - 导航到孙子路线Angular 6
- angular - JSON对象列表的Angular 6 ngbTypeahead过滤器
- java - 想要一个正则表达式,它将验证 java 变量之间只有一个逗号
- prometheus - 普罗米修斯中的范围查询
- javascript - 将输入文本传递给日期选择器的初始设置日期
- python - python3中的ssl ertificate和https连接
- primefaces - Primefaces 宁静主题菜单标签未呈现
- gsm - 使用 GSM 调制解调器向操作员发送 SMS 命令