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
Grazie, contentType: "application/x-www-form-urlencoded "" è ciò che ha funzionato anche per me. –