简体   繁体   中英

Meteor.JS Use External Script (on the server)

I'm new to Meteor.JS and trying to use a script on the server. 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. How can I achieve a similar result server-side to the $.getScript() call?

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.

Nonetheless you can use the http package

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

If you're adding your script in the server folder, don't use var , otherwise it will stay only global to the file scope.

jQuery doesn't exists on the server and for a good reason: you need a DOM to use it. You can use phantomjs to do it: Server-side jquery

Not all code runs on client and server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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