我有一個 index.html
<!DOCTYPE html>
<html>
<head>
<title>Server-side Example</title>
<script src="./CircleArea.js"></script>
</head>
<body>
<input
id="ftpd"
type="button"
value="Calculate"
onclick="CircleArea()"
/>
</body>
</html>
它呼叫 CircleArea.js 檔案。
const PI = 3.14
let radius = 3;
function circleArea(){
var inputField = document.createElement("INPUT");
inputField.setAttribute("type", "text");
inputField.setAttribute("value", (PI*radius*radius));
document.body.appendChild(inputField);
}
module.exports ={circleArea}; // This I added for nodejs
它作業正常。但我現在想在服務器端運行 Index.html。
我添加了 server.js
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./Index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);
console.log('Server running at http://localhost:8000');
現在node server.js
給出錯誤
CircleArea.js:1
Uncaught SyntaxError: Unexpected token '<'
(Index):13
Uncaught ReferenceError: CircleArea is not defined
at HTMLInputElement.onclick ((Index):13:6)
我的問題是我應該如何修改 Index.html 和 CircleArea.js 以在 nodejs 上運行它?
uj5u.com熱心網友回復:
您的代碼與服務器端評估無關。您將 Node.js 用作 Web 服務器。服務器不評估客戶端代碼。它不匯入CircleArea.js. 你不需要
module.exports ={circleArea}; // This I added for nodejs
并且應該洗掉它。這是一個 CommonJS 模塊匯出,不允許在瀏覽器代碼中使用。
Web 瀏覽器發送對index.html. 服務器以Index.html. 瀏覽器評估它。它為這個檔案找到一個腳本標簽./CircleArea.js并發送一個請求。服務器回應內容為 ,Index.html因為服務器中沒有路由。在瀏覽器中打開開發工具以查看問題。服務器對Index.html所有請求使用相同的資料(的內容)進行回應。你必須實作路由。
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
let file = 'Index.html';
if (request.url === '/CircleArea.js') {
file = 'CircleArea.js';
response.writeHead(200, {
'Content-Type': 'application/javascript',
});
} else {
response.writeHead(200, {
'Content-Type': 'text/html',
});
}
fs.readFile('./' file, null, function (error, data) {
if (error) {
response.writeHead(404);
response.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);
console.log('Server running at http://localhost:8000');
這是一個非常基本和簡單的解決方案。您可以將其用于非常簡單的路由。對于更復雜的路由,我推薦像Nest.js這樣的框架
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468436.html
標籤:javascript html 节点.js
