reCaptcha + RequireJS - requirejs

How can I import recaptcha using requirejs. I already tryed several things and nothing works.
I need do that to be able to render it by my own using the method render of reCaptcha once it has been loaded.
require.config({
paths: {
'recaptcha': 'http://www.google.com/recaptcha/api'
}
});
require( ['recaptcha'], function( recaptcha ) {
// do something with recaptcha
// recaptcha.render /// at this point recaptcha is undefined
console.log(recaptcha);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js"></script>

Yes I have a solution for you. So what ends up happening is that recaptcha can't render until it has loaded what it needs from the google api.
So what you need to do is the following (also don't use http/https in your paths):
require.config({
paths: {
'recaptcha': '//www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'
}
});
Now that will allow a callback to be executed after the necessary libraries have been downloaded from the google API.
This callback needs to be global unfortunately.
JS
var requireConfig = {
paths: {
'recaptcha': '//www.google.com/recaptcha/api.js? onload=onloadCallback&render=explicit'
}
};
function render(id) {
console.log('[info] - render');
recaptchaClientId = grecaptcha.render(id, {
'sitekey': '6LdntQgUAAAAANdffhZl0tIHw0fqT3MwNOlAI-xY',
'theme': 'light'
});
};
window.renderRecaptcha = render;
var onloadCallback = function() {
console.log('[info] - onLoadCallback');
if (!document.getElementById('g-recaptcha')) {
return;
}
window.renderRecaptcha('g-recaptcha');
};
requirejs.config(requireConfig);
require(['recaptcha'], function(recaptcha) {
});
HTML
<body>
<form action="?" method="POST">
<div id="g-recaptcha"></div>
<br/>
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.js"> </script>
</body>
I hope that works for you!
Link to Example: https://jsbin.com/kowepo/edit?html,js,console,output

I know this question is a bit old, but I discovered another solution recently in my project that does not require the creation of global methods. This solution ended up being a very simple addition to the OP's first attempt at using Google reCaptcha with RequireJS.
In main.js, add the following: (exactly like the OP has it)
require.config({
paths: {
'recaptcha': 'http://www.google.com/recaptcha/api'
}
});
In your JS file where you're doing the explicit render, do the following:
require( ['recaptcha'], function(recaptcha) {
// render when recaptcha is ready
// injecting recaptcha here will give access to the grecaptcha object and it's ready method
grecaptcha.ready(function()
grecaptcha.render('elementId', {
'sitekey': 'SITE_KEY',
'callback': someCallbackMethod
});
);
});
This worked for me and I believe it's a cleaner solution!

Related

Meteor SSR "Error: Can't render undefined"

I am trying to get server-side rendering using IronRouter and Meteor-SSR in a basic Meteor app. When I load /home in the browser I get the following error:
Error: Can't render undefined
at checkRenderContent (packages/blaze.js:702:11)
at contentAsView (packages/blaze.js:724:3)
at Blaze.toHTML (packages/blaze.js:851:40)
at Object.SSR.render (packages/meteorhacks_ssr.js:208:10)
at [object Object].Router.route.where (main.js:9:20)
at boundNext (packages/iron_middleware-stack.js:408:31)
at runWithEnvironment (packages/meteor.js:1176:24)
at packages/meteor.js:1189:14
at [object Object].urlencodedParser (/Users/roger/.meteor/packages/iron_router/.1.1.1.1q7cd8x++os+web.browser+web.cordova/npm/node_modules1/body-parser/lib/types/urlencoded.js:84:40)
at packages/iron_router.js:886:36
Here's the code for the app:
// main.js
if (Meteor.isServer) {
Router.route('/home', function() {
let html = SSR.render('home');
this.response.end(html);
}, {where: 'server'});
}
if (Meteor.isClient) {
Router.route('/home', function() {
this.render("home")
});
}
Here's main.html:
<head>
<title>SSR Test</title>
</head>
<body>
</body>
<template name="home">
Home
</template>
This happens because your home template is not defined on server. To use SSR package, you need to compile the template in your server with SSR.compileTemplate first, only then you could render it with SSR.render. This is a simple example for you:
if (Meteor.isServer) {
const template = 'Hello {{username}}, <br> Now time is: {{time}}';
SSR.compileTemplate('hello', template);
Router.route('/home', function() {
const html = SSR.render('hello', {
username: 'foo',
time: new Date(),
});
this.response.end(html);
}, {where: 'server'});
}
There is also a better to compile template from static file on server which could be found here

How can i access a nodeJS variable in ejs views in a sails project?

My LoginController.js looks like this:
module.exports = {
getAuthorizationLink: function (req, res) {
res.send({
authorization_link: sails.config.FACEBOOK_LOGIN_URL
})
}
}
I need to redirect to the authorization_link when a button is clicked
<div class="col-md-4 text-center">
<button id="authenticate" class="btn btn-primary">Authenticate Page</button>
<script type="text/javascript">
document.getElementById("authenticate").onclick = function () {
...
};
</script>
</div>
Here you are looking to mix server-side (EJS) & client-side JS code.
It is possible, makes sense to do sometimes but it is not clean.
Once you understand you are doing this. Variable can be passed and accessed.
Using EJS, write JS code for client side e.g.
var auth_link = '<%= authorization_link %>';
this line will become something like below for client-side JS
var auth_link = 'https://fb.com/login';
Now you can use auth_link in client-side JS as required
Also, check res.view for responding with HTML page

Render a component from outside ReactJS

From here :
"The only way to get a handle to a React Component instance outside of React is by storing the return value of React.render."
I need to render a React component outside React and the reason for it I'm going to mention below.
In my node.js, expressJS app, I am using 'react-router-component' and 'react-async'.
In app.js -the file which is supposed to be run ,
var url=require('url');
var App=require('./react/App.jsx');
var app = express();
app.get('*',function(req,res){
//}); SEE EDIT 1 BELOW
var path = url.parse(req.url).pathname;
ReactAsync.renderComponentToStringWithAsyncState(App({path:path}),function(err, markup) {
res.send('<!DOCTYPE html>'+markup);
});
});
In App.jsx,
PostList = require('./components/PostList.jsx');
var App = React.createClass({
render: function() {
return (
<html>
<head lang="en">
</head>
<body>
<div id="main">
<Locations path={this.props.path}>
<Location path="/" handler={PostList} />
<Location path="/admin" handler={Admin} />
</Locations>
<script type="text/javascript" src="/scripts/react/bundle.js"></script>
<script type="text/javascript" src="/scripts/custom.js"></script>
</body>
</html>
});
bundle.js is the browserified file from all the .jsx files.
In PostList.jsx,
var PostList = React.createClass({
mixins: [ReactAsync.Mixin],
getInitialStateAsync: function(cb) {
if(typeof this.props.prods==='undefined'){
request.get('http://localhost:8000/api/cats_default', function(response) {
cb(null, {items_show:response.body});
});
}
},
setTopmostParentState: function(items_show){
this.setState({
items_show:items_show
});
},
render: function() {
return (
<div className="postList" id="postList">
**// Things go here**
<div className="click_me" >Click me</div>
</div>
}
});
PostListRender=function(cart_prods){
var renderNow=function(){
//return <PostList cart_prods={cart_prods}></PostList>
React.renderComponent(<PostList cart_prods={cart_prods}></PostList>,document.getElementById('postList') );
};
return {
renderNow:renderNow
}
};
module.exports=PostList;
In custom.js:
$('.click_me').click(function(){
PostListRenderObj=PostListRender(products_cart_found);
PostListRenderObj.renderNow();
$('odometer').html('price');// price variable is calculated anyhow
});
The page shows well.
EDIT 3 Starts
Now I want to render the PostList component on clicking the click_me div .
EDIT 3 Ends
But when I click on the click_me element, the browser shows script busy, console shows
ReactJS - ReactMount: Root element has been removed from its original container. New container
And the Firebug log limit exceeds.
So why I want to render on click from outside react.js:
I have to run the jQuery Odomoeter plugin on clicking the click_me div. The plugin was not developed as a node middleware although it can be installed the way a middleware is installed and the plugin codebase is saved inside node_modules folder.
Edit2 Starts:
As the plugin is not a node middleware, I cannot require it from inside node. However I can perform the click event (code not shown ) from inside node and run the following code there as well :
$('odometer').html('price');// price variable is calculated anyhow
In this case I include the plugin in the browser with <script /> tag and the browserified bundle.js comes after the plugin script . But the animation is not properly shown. So I take to the client side click event in the custom.js.
If I do not require the plugin to be a middleware from inside node
and just include it in the page before the browserified JS file and
perform the click event inside React, then the odometer animation is
not properly shown.
Edit2 Ends:
So what is the way to render the PostList React component outside React ?
EDIT 1 The }); was quite mistakenly placed there
I cannot understand your question description, but this answers the title question:
How you render React components outside of react?
MyComponent = require('MyComponent')
element = document.getElementById('postList');
renderedComp = ReactDOM.render(MyComponent,{...someProps},element);
// => render returns the component instance.
$(document).on('something, function(){
renderedComp.setState({thingClicked: true})
})
Inside of react you can just call the component.

AngularJS Resolve

I'm creating my frist AngularJS application.
I have a kind of problem with my Index page.
There can be two different templates depending if User is authenticated or not.
My idea is to have a MainController defined before ng-view and a view controller (indexController, aboutController, ...) depending which view is displayed.
I've made a service UserService which mission is to get user's data from my server and serve them to controllers.
The problem is I want my MainController to get the user's data.
I've read things about resolve and promise but it only works with view controllers because it's defined in $routeProvider.
My question is how can I initialize my MainController data before executing my app routes ?
PS : A bit of code to help
index.html
<div id="page" ng-controller="MainController as Main">
<div id="navbar-container" class="shadow1">
<navbar></navbar>
</div>
<div class="row">
<div id="page-container" class="large-12 columns">
<div ng-view></div>
</div>
</div>
</div>
mainController.js
...
define([], function()
{
return angular.module('MyApp.controllers', []).controller('MainController', ['$scope', '$http', 'UserService', function($scope, $http, UserService)
{
// I want this to be defined before executing the app //
$scope.currentUser = UserService.getCurrentUser();
}]);
});
...
userService.js
define(['angular'], function (angular)
{
return angular.module('MyApp.services', []).service('UserService', ['$http', function($http)
{
var _currentUser = null;
var _promise = (_currentUser !== null) ? _currentUser : $http.get('/api/user').success(function(data)
{
_currentUser = data.result;
});
return {
promise : _promise,
getCurrentUser : function()
{
return _currentUser;
},
isAuthenticated : function()
{
return (_currentUser !== null);
},
};
}
]);
});
Maybe there is another way to do what I expect but i'm really a noob with AngularJS. I really would appreciate some help.
Thank you in advance.
I think you have to write $scope.currentUser = UserService.getCurrentUser(); line in run() method of angular js which is first fire when application load
Actually Config blocks run before run blocks. This is only relevant if you are trying to resolve in ng-route or ui-router.
Configuration blocks - get executed during the provider registrations and configuration
phase. Only providers and constants can be injected into configuration blocks. This is to
prevent accidental instantiation of services before they have been fully configured.
Run blocks - get executed after the injector is created and are used to kickstart the
application. Only instances and constants can be injected into run blocks. This is to prevent
further system configuration during application run time.
Line 122

Consuming a Stream create using Node.JS

I have an application, which streams an MP3 using Node.JS. Currently this is done through the following post route...
app.post('/item/listen',routes.streamFile)
...
exports.streamFile = function(req, res){
console.log("The name is "+ req.param('name'))
playlistProvider.streamFile(res, req.param('name'))
}
...
PlaylistProvider.prototype.streamFile = function(res, filename){
res.contentType("audio/mpeg3");
var readstream = gfs.createReadStream(filename, {
"content_type": "audio/mpeg3",
"metadata":{
"author": "Jackie"
},
"chunk_size": 1024*4 });
console.log("!")
readstream.pipe(res);
}
Is there anyone that can help me read this on the client side? I would like to use either JPlayer or HTML5, but am open to other options.
So the real problem here was, we are "requesting a file" so this would be better as a GET request. In order to accomplish this, I used the express "RESTful" syntax '/item/listen/:name'. This then allows you to use the JPlayer the way specified in the links provided by the previous poster.
I'm assuming you didn't bother visiting their site because had you done so, you would have seen several examples of how to achieve this using HTML5/JPlayer. The following is a bare-bones example provided by their online developer's documentation:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.jplayer.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function() {
$(this).jPlayer("setMedia", {
mp3: "http://www.jplayer.org/audio/mp3/Miaow-snip-Stirring-of-a-fool.mp3"
}).jPlayer("play");
var click = document.ontouchstart === undefined ? 'click' : 'touchstart';
var kickoff = function () {
$("#jquery_jplayer_1").jPlayer("play");
document.documentElement.removeEventListener(click, kickoff, true);
};
document.documentElement.addEventListener(click, kickoff, true);
},
loop: true,
swfPath: "/js"
});
});
</script>
</head>
<body>
<div id="jquery_jplayer_1"></div>
</body>
</html>

Resources