所以,我的問題是當我嘗試登錄我的 vue 應用程式時,當我嘗試從中獲取一組物件時,后端會自動停止。
更具體。這是我從資料庫中檢索物件的提取“嘗試”。
let url = utils.url;
let requestParam = utils.globalRequestParameters;
requestParam.method = "GET";
requestParam.body = null;
if (cars.value.length == 0) {
fetch(url "cars", requestParam).then((res) =>
res.json().then(async (res) => {
store.dispatch("Car/fetchCars", res);
fetch(url "users", requestParam).then((users) =>
users.json().then((users) => {
for (let car of res) {
let userCar = Object.values(users).find(
(a) => a.id == car.userId
);
car.userName = userCar.lastName " " userCar.firstName;
}
})
);
})
);
}
And login in view Login.vue
let requestParameters = utils.globalRequestParameters;
requestParameters.method = "POST";
requestParameters.body = JSON.stringify(data);
fetch(utils.url "login", requestParameters).then((res) => {
res.json().then((res) => {
this.mesaj = res.message;
console.log("token:" res.token);
if (res.token) {
localStorage.setItem("token", res.token);
console.log("token:" res.token);
console.log("id:" res.id);
let id = res.id;
requestParameters.method = "GET";
requestParameters.body = null;
this.$store.dispatch("login", true);
fetch(utils.url "users/" id, requestParameters).then(
(res) => {
res.json().then((res) => {
console.log("Jos de tot");
this.$store.dispatch("User/setUser", res);
console.log(this.$store.state.User.user);
this.$router.push("/");
});
}
);
}
});
});
}
},
筆記。汽車是一個計算值,回傳 store.state.cars 和 utils 是
let url = "http://127.0.0.1:3000/";
let globalRequestParameters = {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
redirect: "follow",
referrerPolicy: "no-referrer",
};
module.exports.globalRequestParameters = globalRequestParameters;
module.exports.url = url;
在第一次獲取時,后端會停止,并且還沒有完成獲取。
后端路由是
router.get('/cars', async (req, res) => {
res.json(await functions.getAllCars(req,res));
})
getAllCars = async (req, res) => {
const snapshot = await db.collection("Cars").get();
let cars = [];
snapshot.forEach((doc) => {
let car = {
id: doc.id,
userId: doc.data().userId,
manufacturer: doc.data().manufacturer,
model: doc.data().model,
color: doc.data().color,
plate: doc.data().plate,
price: doc.data().price,
description: doc.data().description
};
cars.push(car);
});
res.status(200).send(cars);
return
};
router.get("/users/:id", async (req, res) => {
res.json(await functions.getUserById(req.params.id, res));
});
getUserById = (id, res) => {
db
.collection("Users")
.doc(id)
.get()
.then((response) => {
let user = {};
user.id = response.id;
user.firstName = response.data().firstName;
user.lastName = response.data().lastName;
user.gender = response.data().gender;
user.jobTitle = response.data().jobTitle;
user.phone = response.data().phone;
user.email = response.data().email;
user.isAdmin = response.data().isAdmin;
res.status(200).send(user);
return
})
.catch((err) => {
res.status(404).send({ message: "User not found" });
return
});
};
用戶被正確檢索,我通過控制臺日志在控制臺中看到它,但我在終端和控制臺中得到的訊息是:


*作為最后的說明。我使用 vue 3、node.js 版本 16.13.0 和 Firestore 作為資料庫。昨天在我的另一臺電腦上一切正常,但我不得不去某個地方使用我的筆記本電腦。也許我的筆記本電腦有問題。我所做的只是安裝正面和背面的模塊
uj5u.com熱心網友回復:
我認為這與 Vue 無關 - 這只是你的 Express 后端代碼的問題
ERR_HTTP_HEADERS_SENT:發送到客戶端后無法設定頭
如上所述這里:
每當您嘗試向同一請求發送多個回應時,就會發生該特定錯誤,并且通常是由不正確的異步代碼引起的。
獲取所有汽車
getAllCars是帶有await內部的異步函式- 一旦await命中(與db.collection("Cars").get()呼叫一起),函式回傳等待于的 Promiseres.json(await functions.getAllCars(req,res));
當資料庫呼叫完成時,將執行該方法的其余部分,包括res.status(200).send(cars)- 這會將cars陣列發送到客戶端并回傳undefined(這就是簡單的return操作)并res.json(undefined)執行導致上述錯誤(您正在嘗試發送第二個回應)
獲取用戶名
你說這個處理程式作業正常,但我真的很懷疑 - 從我看來,這也不應該作業
你用res.json(await functions.getUserById(req.params.id, res));. 要await實際做某事,等待的函式必須回傳一個 Promise(通過使用awaitinside 或顯式隱式地)或一般的“thenable”物件。該getUserById函式不回傳任何內容(return里面的陳述句then()或catch()不計算!...那些是不同的函式)
這個問題可以通過做固定return db.collection("Users").doc(id).get().then(),但那么你會得到同樣的錯誤,如getAllCars情況
正確的模式
- 不要
res.status(200).send()和res.json()一起使用 - 為了理智起見(至少在你真正知道自己在做什么之前)不要將 promise 與
async/await async函式應該回傳資料(不要在return沒有“引數”的情況下使用)
下面的代碼顯示了基于 Promise 和async/await風格(它是“偽代碼”,我沒有測驗過,但希望你能理解)
router.get('/cars', async (req, res) => {
try {
const response = await functions.getAllCars()
res.status(200).json(response);
} catch() {
res.sendStatus(500)
}
})
getAllCars = async () => {
const snapshot = await db.collection("Cars").get();
let cars = [];
snapshot.forEach((doc) => {
let car = {
id: doc.id,
userId: doc.data().userId,
manufacturer: doc.data().manufacturer,
model: doc.data().model,
color: doc.data().color,
plate: doc.data().plate,
price: doc.data().price,
description: doc.data().description
};
cars.push(car);
});
// res.status(200).send(cars); //* should be handled by caller
return cars //* return the data
};
router.get("/users/:id", async (req, res) => {
functions.getUserById(req.params.id)
.then((response) => {
if(response === null)
res.status(404).json({ message: "User not found" });
else
res.status(200).json(response);
})
.catch(er) {
res.status(500).send(er.message)
}
});
getUserById = (id) => {
return db //* return the promise
.collection("Users")
.doc(id)
.get()
.then((response) => {
let user = {};
user.id = response.id;
user.firstName = response.data().firstName;
user.lastName = response.data().lastName;
user.gender = response.data().gender;
user.jobTitle = response.data().jobTitle;
user.phone = response.data().phone;
user.email = response.data().email;
user.isAdmin = response.data().isAdmin;
// res.status(200).send(user); //* should be handled by caller
return user //* return the data
})
.catch((err) => {
return null
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/373146.html
