mrEmpty
mrEmpty

Reputation: 841

Creating a simple Node.js web service for use with AJAX

I have a basic Node.js http server set up as per the docs, I'm trying to create a very simple web service I can talk to with Javascript (AJAX) which I'll then hook up to Arduino. It's a test piece, I may go down the road of something else but this is proving to be fun. Anyway, here is the server-side javascript:

var http = require('http');
var _return = 'Bing Bong';

  http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'application/jsonp'});

    //do stuff
    res.end('_return(\'Hello :-)\' + _return)');
}).listen(process.env.VMC_APP_PORT || 1337, null);

And this is the client side:

function experimentFive(node) {
    console.log('X5 Func started');

    console.log('Calling Node.js service');

    var nodeURL = node;

    $.ajax({
        url: nodeURL,
        dataType: "jsonp",
        jsonpCallback: "_return",
        cache: false,
        timeout: 50000,
        success: function(data) {
            console.log('Data is: ' + data);
            $("#nodeString").text(" ");
            $("#nodeString").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('error : ' + textStatus + " " + errorThrown);
        }
    });
}

experimentFive('http://fingerpuk.eu01.aws.af.cm/');

This works, I get the data back but not as I'd expect. What I'd like to be able to do is change some data server side and receive that back. I get back the string in the res.end plus:

function () {
        responseContainer = arguments;
    } 

Instead of the variable's data. No matter how I try to get that data back, it is either undefined or this response.

From research I think the variable is not having it's data set before the callback fires, so it's empty. But if I set an initial value the data is still undefined.

Am I missing something very simple here? Should I just go back to C#?

Cheers.

Upvotes: 1

Views: 7770

Answers (1)

jrthib
jrthib

Reputation: 1319

One possible way of accomplishing this would be to use ExpressJS with NodeJS to handle routing your endpoints. By doing this you can set up routes such as GET /media/movies/, fire an AJAX request to this route, then have it return JSON data that you can handle on your app.

Here's an example of ExpressJS routing in an app that I made:

var groups = require('../app/controllers/groups');

// find a group by email
app.post('/groups/find', groups.searchGroupsByEmail);

Here is a great tutorial that I used when getting started with Express. It walks through the entire process from installing Node.JS (which you've already done) to setting up the ExpressJS routing to handle incoming HTTP requests.

Creating a REST API using Node.js, Express, and MongoDB

Upvotes: 3

Related Questions