2013-06-04 31 views
5

Neden kısıtlamak için /:parameter içine basit bir JSON dize göndermek çok zor olduğunu bilmek istiyorum. Birçok örneği takip ettim ama somut bir şey bulamadım.Post jQuery JSON Nesne NodeJs Restify

Ön uçta aşağıdaki kod var.

$("#btnDoTest").click(function() { 

    var jData = { 
     hello: "world" 
    }; 
    var request = $.ajax({ 
     url: "http://localhost:8081/j/", 
     async: false, 
     type: "POST", 
     data: JSON.stringify(jData), 
     contentType: "application/javascript", 
     dataType: "json" 
    }); 


    request.success(function(result) { 

     console.log(result); 

    }); 

    request.fail(function(jqXHR, textStatus) { 
     alert("Request failed: " + textStatus); 
    }); 


}); 

ben j/ sonra param bitiştirmek eğer basit metin gönderme başarılı değilim. Ama göndermek istediğim, bu {hello:"world"} gibi bir nesnedir ve nodeJS'de yeniden yapılandırır ve onunla birlikte çalışır.

--edit:

This is my nodejs file 
/* the below function is from restifylib/response.js */ 
var restify = require("restify"); 

/* create the restify server */ 
var server = restify.createServer({ 

}); 


server.use(restify.bodyParser({ mapParams: true })); 

server.use(
    function crossOrigin(req,res,next){ 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With"); 
    return next(); 
    } 
); 


server.post('/j/', function (req, res, next) { 


    //res.send(201,"REceived body: "+JSON.stringify(req.params)); 
    res.send(201,"REceived body: "+JSON.stringify(req.params)); 
    return next(); 
}); 


var port = 8081; 
server.listen(port); 
console.log("Server listening on port " +port) 

Herhangi bir yardım teşekkürler duyacağız.

0x

cevap

6

Sonunda çalıştım.

--Front uç kodu

$("#btnDoTest").click(function() { 



     var request = $.ajax({ 

      url: "http://localhost:3000/j", 
      async: false, 
      type: "POST", 
      data: { 
       blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]} 
      }, 

      contentType: "application/x-www-form-urlencoded", //This is what made the difference. 
      dataType: "json", 

     }); 


     request.success(function(result) { 

      console.log(result); 

     }); 

     request.fail(function(jqXHR, textStatus) { 
      alert("Request failed: " + textStatus); 
     }); 


    }); 

NodeJs hizmetleri

/* the below function is from restifylib/response.js */ 
var restify = require("restify"); 

/* create the restify server */ 
var server = restify.createServer({ 

}); 


server.use(restify.bodyParser()); 
server.use(restify.CORS()); 


server.post('/j/', function(req, res, next) { 

    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With"); 

    // req.params == data on jquery ajax request. 


    res.send(200, JSON.stringify(req.params)); 
    console.log(req.params.blob.ar[2].a) 



    res.end(); 
    return next(); 
}); 


var port = 3000; 
server.listen(port); 
console.log("Server listening on port " + port) 
+0

üzerinde bir seçenek olarak true, 'contentType:' application/x-www-form-urlencoded "'benim için de çalıştı. –

0

Düzeltmeyiniz. Bunu deneyin, iki değişikliğe dikkat edin, JSON.stringify'u kaldırdım ve JSON olarak değil JavaScript olarak application/json'a geçtim.

var request = $.ajax({ 
    url: "http://localhost:8081/j/", 
    async: false, 
    type: "POST", 
    data: jData, 
    contentType: "application/json", 
    dataType: "json" 
}); 

application/javascript sadece JSONP yaparken kullanılmalıdır.

+0

Daha önce böyle bir şey denedim. Çalışmıyor. /OPSİYONLAR/j – Oxnigarth

+0

Belki de çok geç ama eğer hala bilmiyorsanız crossDomain kullanmayı deneyin: ajax – albertpeiro

0

cevabımı ilk!

jQuery:

$.ajax({ 
    url: url, 
    method: 'post', 
    data: JSON.stringify({key:value}), 
    contentType: "application/json" 
}); 

düğüm http:

server.post('/1', function(req, res) { 
    var body = req.body; 
    var dataValue = body.dataKey; 
}); 

neden?

$ .ajax veri sadece sunucuya gönderilecek ne için olduğunu, veri türü tanımlanmamış, bu yüzden JSON.stringify({key:value}) kullanıldığında, veri '{key: "xxx"}' gibi bir dize olarak gönderilir, ve düğüm bir dizgi elde eder, bir json nesnesi değil, dize yapısı bile bir json gibi görünür. ancak node veriyi aldığında contentType: "application/json" $ .ajax'a ekledikten sonra, gerçek bir json nesne tipi verisi olacaktır.