简体   繁体   English

服务器端(nodejs)在html中调用JS function

[英]Call JS function in html on server side (nodejs)

I have an index.html我有一个 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>

It calls the CircleArea.js file.它调用 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

It works fine.它工作正常。 But I now want to run Index.html on the server-side.但我现在想在服务器端运行 Index.html 。

I added server.js我添加了 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');

Now node server.js现在node server.js

gives error给出错误

CircleArea.js:1 
        
       Uncaught SyntaxError: Unexpected token '<'
(Index):13 
        
       Uncaught ReferenceError: CircleArea is not defined
    at HTMLInputElement.onclick ((Index):13:6)

My question is how should I modify Index.html and CircleArea.js to run it on nodejs?我的问题是我应该如何修改 Index.html 和 CircleArea.js 以在 nodejs 上运行它?

Your code has nothing to do with server-side evaluation.您的代码与服务器端评估无关。 You're using Node.js as a web server.您正在使用 Node.js 作为 web 服务器。 The server doesn't evaluate the client code.服务器不评估客户端代码。 It doesn't import CircleArea.js .它不导入CircleArea.js You don't need你不需要

module.exports ={circleArea}; // This I added for nodejs

and should remove it.并且应该删除它。 It's a CommonJS module export and not allowed in browser code.这是一个 CommonJS 模块导出,在浏览器代码中是不允许的。

A web browser sends a request for index.html . web 浏览器发送对index.html的请求。 The server responds with the content of Index.html .服务器响应Index.html的内容。 The browser evaluates it.浏览器对其进行评估。 It finds a script tag for ./CircleArea.js and sends a request for this file.它找到./CircleArea.js的脚本标签并发送对该文件的请求。 The server responds with the content of Index.html because there is no routing in the server.服务器响应Index.html的内容,因为服务器中没有路由。 Open the dev tools in your browser to see the problem.在浏览器中打开开发工具以查看问题。 The server responds with the same data (the content of Index.html ) for all requests.服务器为所有请求返回相同的数据( Index.html的内容)。 You have to implement routing.您必须实施路由。

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');

This is a very basic and simple solution.这是一个非常基本和简单的解决方案。 You can use it for a very simple routing.您可以将它用于非常简单的路由。 For a more complex routing I recommend a framework like Nest.js对于更复杂的路由,我推荐一个像Nest.js这样的框架

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM