简体   繁体   English

Node.js JavaScript-从外部脚本服务器端调用函数

[英]Node.js javascript - call function from external script server-side

I'd like my Node.JS website to send an email every time a form is submitted on the contact-us page. 我希望Node.JS网站每次在与我们联系的页面上提交表单时都发送一封电子邮件。

HTML page HTML页面

<form class="contact_us_form" method="post">
    <button type="submit" >Submit</button>
</form>

Public.js Public.js

router.post('/contact_us', function(req, res, next)
{
   console.log('FORM SUBMITTED FROM CONTACT_US PAGE');
   sendMail();
});

utils.js utils.js

function sendMail() 
{
     //function body
}

When I press the submit button on the html then sendMail is being called but it cannot be found, so the html page and the public.js files are linked properly, but public.js and utils.js are not. 当我按html上的Submit按钮时,将调用sendMail,但找不到它,因此html页面和public.js文件已正确链接,而public.js和utils.js没有。

How would I go about linking the function "sendMail" to Public.js? 如何将功能“ sendMail”链接到Public.js? This function is meant to run on the server, NOT on the client. 此功能旨在在服务器上运行,而不是在客户端上运行。

NodeJS uses the concept of modules . NodeJS使用模块的概念。 You'd export sendMail from utils.js : sendMailutils.js导出utils.js

exports.sendMail = sendMail;

...and import it in public.js : ...并将其导入public.js

var sendMail = require("./utils.js").sendMail;

// ...

sendMail(/*...*/);

or: 要么:

var utils = require("./utils.js");

// ...

utils.sendMail(/*...*/);

Here's a complete example: 这是一个完整的示例:

utils.js : utils.js

function sendMail() {
    console.log("I'm sending mail now...");
}

exports.sendMail = sendMail;

public.js : public.js

var utils = require("./utils.js");
utils.sendMail();

Running it: 运行它:

$ node public.js
I'm sending mail now...

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

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