我有一个 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 上运行它?
您的代码与服务器端评估无关。您将 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这样的框架
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句