2013-06-04 20 views
5

Voglio sapere perché è così difficile pubblicare una semplice stringa JSON in un /:parameter da ripristinare. Ho seguito molti esempi ma non ho trovato nulla di concreto.Post jQuery Oggetto JSON su NodeJs Restify

Ho il seguente codice nel front-end.

$("#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); 
    }); 


}); 

io sono di successo nell'invio di testo semplice se concatenare il param dopo il j/. Ma quello che voglio inviare è un oggetto come questo {hello:"world"} e ricostruirlo di nuovo in nodeJS e lavorare con esso.

--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) 

Tutto l'aiuto sarebbe apprezzato grazie.

0x

risposta

6

Finalmente ho funzionato.

codice finale --Front

$("#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 servizi

/* 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

Grazie, contentType: "application/x-www-form-urlencoded "" è ciò che ha funzionato anche per me. –

0

Non stringa i essa. Prova questo, annota le due modifiche, ho rimosso il JSON.stringify e passato a application/json, come suo JSON e non JavaScript.

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

application/javascript deve essere utilizzato solo quando si esegue JSONP.

+0

Avevo già provato qualcosa del genere. Non funziona. Vedo qualche strano comportamento in post dal momento che viene richiesto in questo modo: /OPZIONI/j – Oxnigarth

+0

Forse troppo tardi ma se ancora non lo sai provare a usare crossDomain: true come opzione sul tuo ajax – albertpeiro

0

la mia risposta prima!

jquery:

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

nodo http:

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

perché?

dati di $ .ajax è solo per cosa inviare al server, il suo tipo di dati non è stato definito, quindi quando si utilizza JSON.stringify({key:value}), i dati verranno inviati come una stringa come '{chiave: "xxx"}', e il nodo riceve una stringa, non un oggetto json, anche se la struttura della stringa sembra un json. ma dopo aver aggiunto contentType: "application/json" in $ .ajax, quando il nodo riceve i dati, sarà un vero tipo di dati di oggetti json.