ApostropheCMS: How to emit Events from Browser to

2019-08-26 19:42发布

I am new to Apostrophe and i cant find a solution for a communication between Client and Server.

I want to get some Data from my MySQL Database into my ApostropheCMS (i have a big Database with over 50k Rows). But i cant find a way, how to communicate between the Browser and the Server.

If i emit an Event from Client, it only triggers apos.on in the Browser, but not on the Server-side.

I cant find any answers in the Documentation, so i really need help.

Thanks for all answers

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-26 20:01

The apos.emit mechanism is just a simple event bus (think of jQuery events) for use within the browser or server, not between them.

For messaging between browser and server, you of course have access to all the usual mechanisms of jQuery and Express, but there are some details to be aware of:

  • On the server side, the easiest way to set up a route in one of your modules is typically to use the route method:

self.route('post', 'do-cool-thing', function(req, res) { // here you can access req.body in the normal Express way, then... return res.send({ some: data, as: json }); }

If your module is called nifty, then this route's URL will be /modules/nifty/do-cool-thing.

However, you can also access self.apos.app, which is the Express app object. So you can write:

self.apos.app.post('/do-cool-thing', function(req, res) { ... });

To create a route without the /module/module-name prefix.

On the browser side, you can communicate in the usual way through $.post, $.ajax and friends. Or, you can use our $.jsonCall plugin:

$.jsonCall('/do-cool-thing', { some: data, sentAs: json, for: you }, function(data) { // JSON response from the server, already parsed for you }, function(err) { // Oh dear, a communications error });

One important thing to remember is that Apostrophe has built-in CSRF protection, to prevent third-party sites from tricking users into taking actions on your website. If you use jQuery's AJAX methods, including our jsonCall plugin, you will automatically participate and have no problems. If you use something else, like fetch, or wish to create an API for the rest of the world, then you'll need to be aware of this and add a CSRF exception.

For more information, see the contact forms tutorial, which covers this in detail.

查看更多
登录 后发表回答