Pulkit
Pulkit

Reputation: 4084

not able to send response from nodejs and capture it in jquery

I am trying to send message in response from nodejs function and then want it to capture by ajax jquery and print it on client id but I am always getting Error [Object object]. Here is my code snippet\

Server.js router.post('/checkUser', function(req, res) {

console.log("checking user");
var db=req.db;
var collection=db.get('userNameCollection');
    console.log("going to execute query:"+req.body.userName);
    collection.find({"user":req.body.userName},{},function(e,list)
    {
        if(list.length==1)
        {
            console.log("user name not available");
            res.writeHeader(200, {"Content-Type": "application/json"}); 
            res.send({data:"user name not available"});

        }
        else{
            console.log("user name available");
            res.writeHeader(200, {"Content-Type": "application/json"}); 
            res.send({data:"user name available"});
        }
        if (e) 
        {
            console.log("error: "+e);
        }
    });

});

index.jade

var myFunction=function(){
                var user = prompt("Please enter your name","User1");
                var url = 'http://localhost:8123/checkUser';
                var message = {userName: user};
                var dataType = 'json';
                $.ajax({
                    type: 'POST',
                    'url': url,
                    'data': message,
                    'dataType': dataType,
                    'success': function(data){
                        alert("Data:"+data.data);
                        console.log("data:"+data);
                    },
                    'error': function(error){
                        console.log('Error: ' + error);
                        alert("ERROR:"+error);
                    }
                })
            }

I am not able to figure out where I am doing mistake

Upvotes: 0

Views: 2517

Answers (2)

Pulkit
Pulkit

Reputation: 4084

I got the solution, its for future reference of others. So the main problem was of Cross Domain policy which was preventing data to be exchanged. To overcome it I simply moved my jquery in $('#testButton').click(function(){}) So here is the code snippet

index.jade

extends layout

block content
    body
        head
            script(src=' https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')

    h1= title
    p Welcome to #{title}
    button(id='testButton') Test Button
    br
    h2#results
script.
$('#testButton').click(function(){
                var message = {userName: "Pulkit Sharva"};
                var dataType = 'application/json';
                $.ajax({
                    url: '/checkUser1',
                    data: message,
                    type: 'POST',
                    dataType: 'json',
                    success: function (data) {
                        var ret = JSON.stringify(data);
                        console.log('Success: '+JSON.stringify(data))
                    },
                    error: function (xhr, status, error) {
                        console.log('Error: ' + JSON.stringify(error));
                    },
                });
            });

index.js

router.post('/checkUser1', function(req, res) {
console.log("From request:"+JSON.stringify(req.body));
res.header("Access-Control-Allow-Origin", "*");
res.send({'data': req.body.userName+' awesome'});

});

enter image description here

Upvotes: 2

azero0
azero0

Reputation: 2310

try this on server side:

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,    Accept");
res.json({"data":'all good'},200);

and this on the client:

$.ajax({
    type: "POST",
    url: "http://localhost:8123/checkUser",
    data:JSON.stringify({"g":"jh"}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){ console.log(data.data);
    },
    failure: function(errMsg) {
        console.log(errMsg);
    }
});

hope this solves your issue

Upvotes: 0

Related Questions