我有一個端點(使用 express),它需要我先進行一些提取。一旦決議回應并使用 res.send ,我就會收到錯誤訊息res.send is not a function。
我嘗試搜索此錯誤,但所有搜索都顯示用戶res,req的順序錯誤。在這種情況下,我的似乎是對的。
為什么在將我的回應轉換為 JSON 后它不是范圍?
router.post("/customerID", async (req, res) => {
return fetch({endPoint}, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Flowspace-Auth": {myToken},
},
body: JSON.stringify({
query: `query {
user {
name
organizationId
}
}`,
}),
})
.then((res) => {
res.json().then((data) => {
console.log(data) // This works
res.send({ data: data }); // res.send is not a function... why, is it not scoped correctly?
});
})
.catch((err) => console.log("unable to fetch:", err));
});
uj5u.com熱心網友回復:
您的外部response變數被內部result變數覆寫。JS 從最內層到最外層尋找變數。因為,res已經在then子句中定義,所以res使用了。
將其更改為resp應該可以作業。
router.post("/customerID", async (req, resp) => {
return fetch({endPoint}, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Flowspace-Auth": {myToken},
},
body: JSON.stringify({
query: `query {
user {
name
organizationId
}
}`,
}),
})
.then((res) => {
res.json().then((data) => {
console.log(data) // This works
resp.send({ data: data }); // resp will belong to outer response
});
})
.catch((err) => console.log("unable to fetch:", err));
});
您可能也想在catch零件中發送一些東西。
uj5u.com熱心網友回復:
您正在對發送方法不可用的 fetch api 呼叫的回應呼叫發送方法。在下面找到正確的代碼。
router.post("/customerID", async (req, res) => {
return fetch(
{ endPoint },
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Flowspace-Auth": { myToken },
},
body: JSON.stringify({
query: `query {
user {
name
organizationId
}
}`,
}),
}
)
.then((response) => {
response.json().then((data) => {
console.log(data); // This works
res.send({ data: data });
});
})
.catch((err) => console.log("unable to fetch:", err));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390750.html
標籤:javascript 表达 拿来
下一篇:環境變數未定義在頂部定義
