CrazySynthax CrazySynthax - 1 year ago 90
Ajax Question

JSONP - express: Why does the browser ignore the request?

I wrote the following HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>

<body>
<script src='http://localhost:3000?callback=mycallbackFunction'> </script>
<script>
function mycallbackFunction(data) {
alert('here');
alert (data['a']);
}
</script>
</body>

</html>


As you can see, the script tag includes a JSONP request to a remote server.

In addition, I wrote the following node.js file and ran it as a server:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
res.jsonp({'a': 'blabla'});
});

app.listen(3000);


After I had run the node.js file and opened the browser with the html page, I expected to see a pop-up window of alert. But, no. I didn't see anything.

The Network Tab in Developer Tools shows that the request has been accepted:
enter image description here

Do you know how to resolve it?

Answer Source

You need to swap the order of your <script> elements.

Explanation:

Express is correctly serving a script that looks like myCallbackFunction({'a': 'blabla'}), which is exactly what you hoped for. However, this script runs immediately, and myCallbackFunction has yet to be defined, so nothing happens. Then, in the next <script> block, you define myCallbackFunction, but this is useless, since the (failed) call has already happened in the previous <script>.

Also, you have a case mismatch on the C in mycallbackFunction -- make sure the capitalization agrees between the callback parameter and the name of your function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download