我是 node.js 和 mySQL 的新手,我克隆編碼餐廳網站。所以我制作了資料庫并制作了服務器。
var app=express();
app.listen(9999,function(){ //I'm using 9999 port and I use Localhost
console.log('Server is running');
})
//connect mySQL
var client=mysql.createConnection({
user:'root',
password:'pswd' //for Question
});
我使用 9999 埠并在 localhost 上打開我的服務器。
我有html。它只是測驗 html 檔案(minuk_test.html),當我請求“/store/restaurant_info”時,我想使用 json 接收資料。
-- main.js --
app.get('/store/restaurant_info',function(request,response){
client.query('SELECT * FROM RESTAURANT_INFO',function(error,result,fields){
if(error){
console.log('Query syntax error');
}else{
response.json(result);
console.dir(result[0].name);
console.log('check sending data');
}
});
});
app.get('/Project/html/minuk_test.html',function(request,response){
fs.readFile('../html/minuk_test.html','utf-8',function(error,data){
if(error){
console.log('Loading minuk_test.html is failed');
}
response.send(data);
})
})
這是我的html代碼。-- html檔案--
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API TEST</title>
<link rel="stylesheet" href="/minuks_test.js">
</head>
<body>
<h1>Test</h1>
<div id="restaurant">
<span></span>
<span></span>
</div>
</body>
</html>
這是我的javascript
--javscript 檔案--
import fetch from "node-fetch";
function getAPI(){
const url=`http://127.0.0.1:9999/store/restaurant_info`;
fetch(url)
.then(response=>{
console.log(response);
response.json();
})
.then(data={
console.log(data);
});
}
getAPI();
我希望當我輸入“minuk_test.html”時,html 會執行 javascript 檔案。在 javascript 檔案中,使用 get 請求購買 url。
但我有兩個問題。
首先,我運行我的服務器。如果 html 運行 javascript 檔案,則輸入 localhost:9999/Project/html/minuk_test.html。和對 /store/restaurant_info 的 javascript 檔案請求。然后服務器控制臺列印結果 [0].name 和“檢查發送資料”,但控制臺很清楚。
其次,我在服務器打開的情況下運行 javascript 檔案。然后 console.log(response) 就在這里
Response {
size: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
stream: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
boundary: null,
disturbed: false,
error: null
},
type: 'default',
url: 'http://127.0.0.1:9999/store/restaurant_info',
status: 200,
statusText: 'OK',
headers: {
connection: 'close',
'content-length': '8035',
'content-type': 'application/json; charset=utf-8',
date: 'Mon, 30 May 2022 11:53:15 GMT',
etag: 'W/"1f63-IYBGYq/MlY5TBn49Gp7cFQ7aH A"',
'x-powered-by': 'Express'
},
counter: 0,
highWaterMark: 16384
}
}
undefined //console.log(data);
response.size 為 0。正常嗎?并且 console.log(data) 未定義
但在郵遞員中,

郵遞員可以接收 json 資料。
我不明白為什么我的 html 無法接收 json。請幫我。
uj5u.com熱心網友回復:
因為 html 檔案中沒有包含 javascript 檔案,并且沒有包含它是因為您沒有在 Web 服務器上提供靜態檔案,所以沒有運行(另外,它不是stylesheet, 而是script標簽)
如果您行內javascript,它應該可以作業。此外,在您使用的瀏覽器fetch和node-fetch服務器端):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API TEST</title>
<script>
function getAPI(){
const url=`http://127.0.0.1:9999/store/restaurant_info`;
fetch(url)
.then(response=>{
console.log(response);
response.json();
})
.then(data={
console.log(data);
});
}
getAPI();
</script>
</head>
<body>
<h1>Test</h1>
<div id="restaurant">
<span></span>
<span></span>
</div>
</body>
</html>
但是您應該設定靜態檔案,請參見此處:
https://expressjs.com/en/starter/static-files.html
此外,您可以設定自己的路由,無需擴展名,也可以用于.sendFile提供特定檔案而不是fs,但您需要提供絕對路徑(通過path模塊):
看這里:
http://expressjs.com/en/api.html#res.sendFile
app.get('/my-route', function(request, response, next) {
response.sendFile(require('path').join(__dirname, '../html/minuk_test.html'), function(err) {
if (err) {
next(err)
} else {
console.log('Sent:', fileName)
}
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484450.html
下一篇:工廠模式
