Meteor server api using iron router returns HTML not the response - rest

I have a simple Meteor app just the basic meteor create test. I want to be able to route traffic to the "/" directory to a template.
I want to be able to route data from a facebook web-hook to a simple js response.
My issue is that when I fire the web-hook URL using postman it returns HTML and not my response.
I've tried many different options for other posts I have read but now have the most basic version to just get it working.
Here is the code I've used
main.html
<head>
<title>test</title>
</head>
<body>
</body>
<template name="home">
<form class="new-message">
<input type="text" name="message" placeholder="Testing">
</form>
</template>
main.js:
import { Meteor } from 'meteor/meteor';
import { Router } from 'meteor/iron:router';
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', function () {
this.render('home');
});
Router.route('/webhooks/facebook', function() {
var request = this.request;
var response = this.response;
response.end('webhook was called');
}, {
where: 'server'
});
All other files are exactly how they are created with meteor create.
I'm on Meteor version 1.8.1
I'm using postman to test the web-hook this is the created GET URL:
https://------.ngrok.io/webhooks/facebook?hub.verify_token=mytoken&hub.challenge=1234567&hub.mode=subscribe
code omitted to keep ngrok from getting slammed.
This is the response I'm getting:
<html>
<head>
<link rel="stylesheet" type="text/css" class="__meteor-css__"
href="/merged-stylesheets.css?hash=6b1f9f6fb78291ae58da8ec4f36476931155453c">
<title>simplechat</title>
</head>
<body>
<script type="text/javascript">
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.8.1%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22development%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Flocalhost%3A3000%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdate%22%3A%7B%22versions%22%3A%7B%22web.browser%22%3A%7B%22version%22%3A%22b22f1ad86c0a904c992885256b7de72ed2863e1d%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22fc4ded0006de942fe57524f94d500abeb4569d6f%22%7D%2C%22web.browser.legacy%22%3A%7B%22version%22%3A%222571a76ffc344fbc5b40ade303255cbbc59e2682%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22dc1e886b7786e303655c010220e9f502e82dcf1c%22%7D%7D%2C%22autoupdateVersion%22%3Anull%2C%22autoupdateVersionRefreshable%22%3Anull%2C%22autoupdateVersionCordova%22%3Anull%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%7D%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%2C%22isModern%22%3Afalse%7D"))
</script>
<script type="text/javascript" src="/packages/meteor.js?hash=857dafb4b9dff17e29ed8498a22ea5b1a3d6b41d"></script>
<script type="text/javascript" src="/packages/meteor-base.js?hash=29010b127daf4ebacaaf9db9b8a61487e57d7d86">
</script>
<script type="text/javascript" src="/packages/mobile-experience.js?hash=2751f9ec11102d1106042c462b340c3fcfcb1990">
</script>
<script type="text/javascript" src="/packages/modules-runtime.js?hash=d3c3e5d67c95f97a60888bda7373292efad3be5e">
</script>
<script type="text/javascript" src="/packages/modules.js?hash=e8b7455d5562fec1444a3c6882cdc6639055cfca"></script>
<script type="text/javascript" src="/packages/modern-browsers.js?
<script type="text/javascript" src="/packages/autoupdate.js?hash=6d56c0f3a885390c688b4f3f893d96d1280fd0ee"></script>
---- Cut out all of the other script calls to keep this short -----
<script type="text/javascript" src="/app/global-imports.js?hash=1f8a1ae2e343994912f72f1dc6eec1ca7df24cae"></script>
<script type="text/javascript" src="/app/app.js?hash=70cfa37cd2f85e533f69d7312d02ef8984eae01a"></script>
</body>
</html>
So basically it returns HTML.
I'm sure I'm missing something simple.
Thanks in advance for you help. Usually I wait till I have exhausted all other options before posting here. And I'm sure I have tried every other example given here on StackOverflow.
My desired result is simple to just return a HTTP response "webhook was called" instead of the HTML garbage.

You could use somethings like this :
Router.map(function(){
this.route("routeName", {path: "/url/:param1/:optionalParam?,
where: "server",
action: function(){
var param = this.params.param1;
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
//authenticate call and decrypt body
if (this.request.method == 'POST') {
//do something
}
if (this.request.method == 'GET') {
//do something
}
}
});
this.route("abc", {path: "/api/get/user/activity/:temp1",
where: "server",
action: function(){
//proceed as above
}
});
});
For help, read through https://iron-meteor.github.io/iron-router/#server-routing
The router file should be saved inside the server folder (for server-side routes)

Haven't used iron route in a long time but from what I remember you want to change your server side route to the following as it is for restful routes.
Router.route('/webhooks/facebook', { where: 'server' })
.get(function () {
// GET
})
.post(function () {
// POST
})
.put(function () {
// PUT
})

For others who have been struggling getting both server and client routes to work on the same Meteor app here is the solution.
Iron routers newest version requires all server side routes to be on the server side and you must fire them from the startup.
All client routes are added on the client side and included in the main.js on the client side.
My simple test was this:
meteor create test
Then in clients/main.html replace the current code and add a simple template as follows:
<head>
<title>newroutetest</title>
</head>
<body>
</body>
<template name="home">
<h1>Home</h1>
</template>
Then in the client/main.js add your client routes as follows:
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', {
template: 'home'
});
Now we setup the server side route in the file server/main.js you add the route in the startup section as follows:
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
Router.route('/webhook', function () {
var req = this.request;
var res = this.response;
res.end('hello from the server\n');
}, {where: 'server'});
});
That's It
I hope this helps others who have been struggling with this.

Related

How do I transform nested components in separate jsx files with babel?

I haven't used React in several months, and tonight I was trying to write jsx that is automatically compiled to jsx by babel according to these directions.
I have two files like this:
Parent.jsx
var Parent = React.createClass({
render: function() {
return (<Child></Child>);
}
});
and
Child.jsx
var Child= React.createClass({
render: function() {
return (<span>CHILD</span>);
}
});
I am using babel to monitor the files for changes and output new js files when needed, and it always renders the Child component as React.createElement("Child", null) instead of React.createElement(Child, null) like I expect.
I'm new to babel and node in general and can't find a way to get this jsx transform to work as I expect. Is there something I'm missing? I feel like this pattern used to work, but I've never tried it with anything like babel before.
It took me what felt like forever to figure this out, but it turns out you can just load all the files from the HTML and then nest them later on.
HTML:
<html lang="en">
<head>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"></script>
</head>
<body>
<div id="root"></div>
<div id="test"></div>
</body>
<script src="./Test3a.jsx" type="text/babel"></script>
<script src="./Test3b.jsx" type="text/babel"></script>
<script type="text/babel">
ReactDOM.render(<Ostrich />, document.getElementById("root"));
</script>
<script type="text/babel">
ReactDOM.render(<Monkey />, document.getElementById("test"));
</script>
Test3A.jsx:
window.Ostrich = function() {
return (
<div>
Ostriches
</div>
);
}
window.Monkey = function() {
return (
);
}
Test3A.jsx:
window.MoreMonkeys = function() {
return (
<div>
That's a lot of Monkeys.
</div>
);
}
This is for non-webpack "React JS", or more accurately Babel/JSX "without" ReactJS. It may not be a perfect solution, but hopefully it helps.

Phonegap App not including javascript files

Javascript files are not being pulled into my Phonegap app. This is a recent problem that is quite frankly driving me insane. This is the top of my index.html file:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD90W6MypWGP6s4luD2kQHhZ9IFQrfr04g&sensor=true"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/facebook.js"></script>
<script type="text/javascript">
app.initialize();
</script>
This is my facebook.js file that I'm trying to pull in:
$(document).on('ready' , function(){
console.log('ready')
function onDeviceReady(){
console.log('test')
var plugin = new CC.CordovaFacebook();
plugin.init('***************', 'myapp',
['email'],
function(response){console.log(response)},
function(failure){console.log(failure)});
var loginButton = $('#login-with-facebook');
loginButton.on('click' , function(e){
e.preventDefault();
plugin.login(function(token) {
console.log("Access token is: " + token);
}), function(failure){console.log(failure)});
})
}
if (window.cordova.logger) {window.cordova.logger.__onDeviceReady();};
onDeviceReady();
document.addEventListener("deviceready", onDeviceReady, false);
})
I can't console.long anything in the facebook.js file. What's driving me even more crazy is that it's worked on occasion. Are my files out of order? Also, I only seem to be running into this issue after installing one of the cordova facebook plugins. Does anybody know what's going on here?
Because you define your onDeviceReady function inside an anonymous event handler function, it won't be available until the DOM is loaded (and shouldn't only be accessible from within the event handler. This would only work properly if the device is ready before the DOM loads and only because onDeviceReady is manually invoked in the onDocumentReady event handler. Replace your facebook.js with the following.
function onDeviceReady(){
console.log('test')
var plugin = new CC.CordovaFacebook();
plugin.init('443530475777959', 'spencerspiegelapp',
['email'],
function(response){console.log(response)},
function(failure){console.log(failure)});
var loginButton = $('#login-with-facebook');
loginButton.on('click' , function(e){
e.preventDefault();
plugin.login(function(token) {
console.log("Access token is: " + token);
}), function(failure){console.log(failure)});
})
}
$(document).on('ready' , function() {
console.log('ready')
document.addEventListener("deviceready", onDeviceReady, false);
if (window.cordova.logger) {
window.cordova.logger.__onDeviceReady();
}
});

xfbml registration plugin validation error

I used Facebook's demo scripts to understand registration plugin' system. I use this code:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>Home</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId=285180546708&xfbml=1"></script>
<fb:registration redirect-uri="http://basarozcan.com/store_userdata.php"
fields='[{"name":"name"},
{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"></fb:registration>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
function validate_async(form, cb) {
$.getJSON('validate.php?username=' + form.username,
function (response) {
if (response.error) {
// Username isn't taken, let the form submit
cb();
}
cb({ username: 'That username is taken' });
});
}
</script>
</body>
</html>
I opened the page and write username but script can not validate username and firebug show an error. Error is:
Permission denied to access property 'Arbiter'
if (p == parent || !p.Arbiter || !p.JSON) {
How can I solve this problem?
Thanks
I think you need to use HTTPS:
<script src="https://connect.facebook.net/en_US/all.js#appId=285180546708&xfbml=1"></script>

When i select CheckBox().I need to update its value into DB - MVC2,AJAx,JQuery

Please find the code which i tried to update the DB using MVC2.But unable to update
View Page with Ajax Code
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
</script>
<div class="bgDiv">
<input id="cbID" type="checkbox" name="SelectedObject" value="cbValue" />
Controller page code
public ActionResult About(string str)
{
AboutModels ObjAM = new AboutModels();//model class name
polloptions = ObjAM.dbValue(str);//call the model function to udate the table
return View();
}
Please advice
you should either declare your event handler in ready function or declare it with live or delegate methods like
<script language="javascript" type="text/javascript">
$(function(){
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
});
});
</script>
the problem is that your script is running before the required checkbox is rendered so putting it in ready will wait until document is ready or live will bind it on document level where the event will reach through propogation

dialog does not come up after uploading asp.net mvc 2

my dialog does not popup after successfull upload? the upload works fine but $("#dialog-confirm").dialog does not work?
<h2>
upload Data</h2>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script src="../../Content/jquery-ui-1.8.12.custom/js/jquery-ui-1.8.12.custom.min.js"
type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.8.12.custom/css/ui-lightness/jquery-ui-1.8.12.custom.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: '<h1><img src="/Content/busy.gif" /> uploading file...</h1>' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
//alert(result.message);
//does not popup??
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Ok":
function () {
alert('ok');
$(this).dialog("close");
}
,
Cancel: function () {
$(this).dialog("close");
}
}
});
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Home")%>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file</legend>
<label>
File to upload:
<input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
</form>
public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
{
// TODO: Add your business logic here and/or save the file
System.Threading.Thread.Sleep(2000); // Simulate a long running upload
// Return JSON
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I see that you are using the jquery.form plugin for AJAXifying the form and returning JSON from your controller action. Here's what the documentation says about this scenario:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads.
So for this to work the response from the server needs to look like this:
<textarea>{ message: 'file uploaded successfully' }</textarea>
Is it what this custom FileUploadJsonResult is doing in your controller action?