简体   繁体   English

Meteor.JS使用外部脚本(在服务器上)

[英]Meteor.JS Use External Script (on the server)

I'm new to Meteor.JS and trying to use a script on the server. 我是Meteor.JS的新手,正在尝试在服务器上使用脚本。 When I needed a script on the client, I just used jQuery's $.getScript(my-script.js) to load it, but on the server, I get a $ is not defined error, presumably because jQuery isn't loaded on the server. 当我需要客户端上的脚本时,我只是使用jQuery的$ .getScript(my-script.js)来加载它,但是在服务器上,我得到了一个$ is not defined错误,大概是因为jQuery未加载到服务器。 How can I achieve a similar result server-side to the $.getScript() call? 如何在服务器端获得与$ .getScript()调用类似的结果?

You don't need to load external scripts manually, you can just add them as files into your project folder. 您不需要手动加载外部脚本,只需将它们作为文件添加到项目文件夹中即可。 All files in your folders will be loaded by meteor. 您的文件夹中的所有文件将由流星加载。 See the Namespacing section of the documentation for directions on how to make definitions available globally rather than just internally to the script.: 有关如何使定义全局可用而不是仅在脚本内部可用的说明,请参见文档的名称间隔部分:

// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};

// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};

I wouldn't advice the process, especially on the server. 我不会建议该过程,尤其是在服务器上。 This exposes you to lots of risks. 这使您面临很多风险。 The .getScript method uses eval which creates a remote code execution vulnerability on your app. .getScript方法使用eval在应用程序上创建一个远程执行代码漏洞。

Nonetheless you can use the http package 不过,您可以使用http包

meteor add http

Then you can retrieve the script & execute it: 然后,您可以检索脚本并执行它:

var jsCode = HTTP.get("<full url>").content;
eval(jsCode);

If you're using a third party script, the best practice is to create a package to wrap it. 如果您使用的是第三方脚本,则最佳实践是创建一个包装它的程序包。 In the package you've to export the global variables of the package: api.export('GlobalVariable') 在包中,您必须导出包的全局变量: api.export('GlobalVariable')

If you're adding your script in the server folder, don't use var , otherwise it will stay only global to the file scope. 如果要将脚本添加到服务器文件夹中,请不要使用var ,否则它将仅在文件范围内保持全局。

jQuery doesn't exists on the server and for a good reason: you need a DOM to use it. jQuery在服务器上不存在,原因很充分:您需要DOM才能使用它。 You can use phantomjs to do it: Server-side jquery 您可以使用phantomjs来做到这一点: 服务器端jquery

Not all code runs on client and server. 并非所有代码都在客户端和服务器上运行。

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

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