我試圖將簡單資料從我的服務器傳遞到另一個 html 頁面上呼叫的 javascript 檔案。我正在測驗從服務器發送單個字串,但不確定如何接收它。服務器如下:
const express = require('express')
const app = express()
const port = 3000
app.use(express.static("./assets"));
app.get('/', (req, res) => {
//res.send('Hello World!')
res.sendFile('./main.html', { root: __dirname });
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
app.get('/get-test', async (_req, res) => {
try {
const test_string = "get-test request string";
return res.send(test_string);
} catch (e) { throw e; }
});
在另一個 javascript 檔案中,我有以下內容:
async function testing() {
const response = await fetch('/get-test');
console.log(response);
}
testing();
這console.log給了我一個完整的物件,點擊它我似乎無法在test_string任何地方找到我的:

所以我相信get請求有效,但我如何實際訪問我想要的資料?
uj5u.com熱心網友回復:
您需要在呼叫await response.text()之前呼叫console.log它。
uj5u.com熱心網友回復:
所以在這個函式中:
async function testing() {
const response = await fetch('/get-test');
console.log(response);
}
testing();
你需要把await 里面的console.log
像這樣:
async function testing() {
const response = await fetch('/get-test');
console.log(await response);
}
testing();
為什么 ?
由于 javascript 在檢索資料時是異步的,因此會有延遲。這就是他們實作 async / await 和 promises 的原因。因此,當您嘗試使用 fetch 發出 get 請求時,您需要等待回應。但是回應也是一個承諾,這意味著您還需要等待回應。當您嘗試將回應處理為 json 時,這更有意義。
一個小技巧
當 console.log 沒有回傳錯誤,但也沒有資料時。可能是因為 promise 問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350166.html
標籤:javascript 节点.js 表达
上一篇:axios傳遞引數如何獲取請求?
