ApostropheCMS: How to emit Events from Browser to Server

送分小仙女□ 提交于 2019-12-11 17:09:30

问题


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:


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.



来源:https://stackoverflow.com/questions/49601647/apostrophecms-how-to-emit-events-from-browser-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!