我知道最好使用 expressJS,但我想了解核心 NodeJS API。我想創建一個沒有任何模塊的最簡單的服務器。我們到處都可以找到只發送 html 檔案的服務器代碼:
const fs = require('fs')
const http = require('http')
const path =require('path')
const server = http.createServer((req,res)=>{
fs.readFile(path.join(__dirname,'index.html'),(err,data)=>{
if (err){
throw err
}
res.writeHead(200,{'Content-Type':'text/html'})
res.end(data)
})
}).listen(8080, () => {
console.log('Server running on port 8080')
})
server.on('request', (req, resp) => {
if(req.url === '/' && req.method === 'GET') {
data=fs.readFileSync(__dirname '/index.html')
resp.writeHead(200, {
'Content-Type': 'text/html',
})
return resp.end(data)
}
})
如果我嘗試發送 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1 id="text">Hello!</h1>
<button id="change">Change</button>
<script src="index.js"></script>
</body>
</html>
腳本檔案 index.js 不加載。index.js 的例子:
const text=document.getElementById('text')
const change = document.getElementById('change')
const col1='rgb(255, 0, 0)'
const col2='rgb(0, 0, 0)'
change.addEventListener('click', () => {
if (text.style.color===col1){
text.style.color=col2
}else{
text.style.color=col1
}
})
如何通過純 Node.js 發送兩個檔案:index.html 和 index.js?ExpressJS 的類似問題:Node.js serve HTML, but can't load script files in serve page , but there used Express, 在這個問題中我想使用純 node.js。
uj5u.com熱心網友回復:
我認為你需要在你的server.on('request', ...). 當前的 if 陳述句只處理index.html
你可以試試這個,我還沒有測驗代碼,但從邏輯上講它應該可以作業:
server.on('request', (req, resp) => {
if(req.url === '/' && req.method === 'GET') {
data=fs.readFileSync(__dirname '/index.html')
resp.writeHead(200, {
'Content-Type': 'text/html',
})
return resp.end(data)
}
// add this code
if(req.url === '/index.js' && req.method === 'GET'){
data=fs.readFileSync(__dirname '/index.js')
resp.writeHead(200, {
'Content-Type': 'application/javascript',
})
return resp.end(data)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477059.html
標籤:javascript 节点.js http
