Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
796 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...