krevativ
krevativ

Reputation: 550

ajax GET call with node.js / express server

I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:

  $('#words').bind('keyup', function(){
    getMatchingWords($('#words').val(), function (data){
      console.log('recieved data');
      console.log(data);
      $('#ajaxresults').show();
    });
  });

function getMatchingWords(value, callback) {
    $.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
        type: 'GET',
        dataType: 'json',
        success: function(data) { if ( callback ) callback(data); },
        error  : function()     { if ( callback ) callback(null); }
    });
}

and here ist my serverside route:

app.get('/matchword/:value', function(req, res) {
      console.log(req.params.value);
      res.writeHead(200, {'content-type': 'text/json' });
      res.write( JSON.stringify({ test : 'test'}) );
      res.end('\n');
});

it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help

Upvotes: 0

Views: 9494

Answers (3)

urfx
urfx

Reputation: 184

hey better late than never...

I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.

first of all I put your url into a local variable. As I don't think that was your problem. Particularly if your express / node log was showing a 200 response. then the url was fine...

It seems your function wasn't returning data (correct ?) if so try this.

var search_url = "..."// your url

function getMatchingWords(value, callback) {
    $.ajax(search_url, {
        type: 'GET',
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            var returned_data = data;
            console.log("returned_data ="+returned_data);//comment out or remove this debug after test
            callback(returned_data);
        },
        error: function( req, status, err ) {
            console.log( 'something went wrong', status, err );
        }
    });
}

you might also need to add / modify your headers subject to the set up...

        headers : { Authorization : auth },
        type: 'GET',
        dataType: 'json',  
        crossDomain:true,

the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...

Upvotes: 1

Cris-O
Cris-O

Reputation: 5007

Change

$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {

to

$.ajax('/matchword' + value + '/', {

Upvotes: 7

Dave Ward
Dave Ward

Reputation: 60590

What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.

Upvotes: 2

Related Questions