我有以下问题:我想将一些 Json 数据发布到我的 Node.js 服务器,在我的服务器中,我想检查电子邮件是否有特定的结尾以及名称是否是电子邮件的一部分。如果不是,我想向客户端发送错误消息。问题是,由于捕获,当邮件/名称不匹配时,它只会提醒“出现问题”。我怎样才能使它工作,我可以从服务器向客户端发送特定的错误消息?
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(jsonObject),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
window.location.assign(`http://localhost:3000/blog/list`);
} catch(e) {
console.error(e);
alert("Something went wrong");
}
const post = {
author: req.body.author,
email: req.body.email,
};
var mail = req.body.email
var name = req.body.author;
var validMail = mail.indexOf("gmail.com");
var names = name.split(' ');
var i = 0;
var x = false;
var validNames = [];
var error = "a error";
while (i < names.length) {
validNames.push(mail.indexOf(names[i].toLowerCase()))
if (validNames[i] > -1) {
x = true;
}
i++;
}
if (validMail > -1 && x == true) {
posts.push(post);
res.send(post);
} else {
res.send(error);
}
代码示例是否真的在错误的电子邮件中显示“出现问题”?因为它看起来不像。fetch 抛出的唯一方法是死服务器或非 json 响应。
将错误返回给您可以解析和使用的客户端,您可以这样做
res.status(500).send({error: 'hello i failed'});
然后在客户端你可以这样做来处理错误:
const json = await response.json();
if (json.error) {
console.log(json.error);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句