【发布时间】:2020-06-28 17:34:57
【问题描述】:
我正在尝试在前端构建一个逻辑来区分重定向和 JSON 响应,最终目标是,如果响应是重定向到该页面,并且如果响应有数据,那么它将呈现页面上的数据。
注意:如果后端以 res.redirect 或 res.json 的形式发送响应,它工作正常,但是当我必须首先检查来自后端的响应时,我正在苦苦挣扎(如下面的代码) ,我想好像我可以在前端使用 if else 语句来在 res.json 和 res.respond 之间进行恶心,我尝试过 .then(res.redirect=>{…}).then(res.json=>{ }) 但如果我使用正确的逻辑,它看起来不像。 请有任何建议,谢谢 :slightly_smiling_face:
我的前端代码片段是。
const request = new Request("http://localhost:5000/api/newuser", options);
(async () => {
const incomingdata = await fetch(request)
*// below i differetiated the incoming response as if it is res.redirect or res.json data but didnt work*
.then((res.redirect) => {
window.location.href = res.url;
})
.then((res.json) => {
console.log("cannot find data");
})
.catch((err) => console.log("err"));
我的银行结束代码的片段是,
connection.query("SELECT * FROM users WHERE email=?;", [x1.Email], function (
err,
results
) {
console.log("74",results, err);
console.log("75",results[0].email);
if (err) throw err;
else {
if (results[0].email && results[0].password) {
console.log("79",results[0].email);
//console.log(results[0]);
if (results[0].password == x1.password)
res.redirect("http://localhost:3000/");
else {
res.json({
data: "invalid password",
});
}
} else res.redirect("http://localhost:3000/about");
}
});
});
【问题讨论】:
-
对于重定向,您可以检查 HTTP 代码是否在
res.status中提供的 300 范围内。它不需要点符号,所以,你可以使用then(res => { if(res.status >= 300 && res.status < 400){ // redirect } else { return res.json(); } }) .then(data => { //handle your json data });
标签: javascript node.js reactjs