/ / Accesso alla stringa sul server Node.js da Ajax Post Request - javascript, node.js, ajax, express

Accesso alla stringa sul server Node.js da Ajax Post Request - javascript, node.js, ajax, express

Questo è il mio primo progetto che lavora con ajax e node.js e finora tutte le mie richieste POST sono state fatte attraverso l'invio di moduli.

Ora sto cercando di usare $.ajax inviare a POST e passare la stringa "cocktailid" per il server.js da usare dopo un div click().

Mi stavo chiedendo quale sarebbe stato il modo più semplice per ottenere questo risultato.

Codice Ajax

$(".col-sm").click(function(){
//Append to console a log that cocktail div has been clicked.
console.log("Cocktail Clicked.");
console.log(this);

//Create variable to hold id of cocktail div clicked
var cocktailid = $(this).attr("id");
cocktailid = cocktailid.replace(/s+/g, "_");
cocktailid = cocktailid.replace(/"/g, "");
alert(cocktailid);

$.ajax({
type: "POST",
url: "/adddrink",
data: { "field1": cocktailid},
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
console.log("success");
console.log(cocktail + "sent.");
console.log(JSON.stringify(data));
}
});
})
};

Server.js

app.post("/adddrink", function(req, res){
console.log(req.body);
});

Ho provato a inviare i dati in alcuni formati diversi e ho avuto diversi problemi, attualmente il mio server mostra il seguente errore:

SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:157:10)
at parse (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:83:15)
at /home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:224:16)
at done (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:160:13)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:152:19)

In questo momento voglio solo mostrare che posso accedere alla stringa sul server nodo.

Ho provato a cercare una soluzione e, dopo i miei tentativi, mi aspetto che io abbia davvero complicato troppo quello che sto cercando di ottenere, qualsiasi aiuto sarebbe molto apprezzato!

risposte:

0 per risposta № 1

Devi usare: JSON.stringify sopra data

$.ajax({
type: "POST",
url: "/adddrink",
data: JSON.stringify({
"field1": cocktailid
}),
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {}
});

Senza di esso il carico utile è field1=yes invece di {"field1":"yes"} è per questo che stai ottenendo SyntaxError: Unexpected token # in JSON at position 0 perché non stai postando un JSON valido.

Per un errore più dettagliato, è possibile aggiungere un middleware di gestione degli errori dopo body-parser per gestire gli errori JSON.

app.use(bodyParser.json());

app.use((err, req, res, next) => {

// Body parser middleware Error
if(err instanceof SyntaxError) {

// err.body contains the actual body that was posted
// which won"t be a valid JSON.
console.error(`Invalid JSON: ${err.body}`);

return res
.status(400) // Bad request
.send({
message: "Invalid JSON"
});

}

next();
});