Node.js: richieste AJAX POST con jQuery ed Express

Possiamo utilizzare jQuery per effettuare richieste AJAX POST anche con Express.

Node.js di Gabriele Romanato

Possiamo utilizzare jQuery per effettuare richieste AJAX POST anche con Express.

In Express i parametri POST vengono memorizzati nell'oggetto body della richiesta. L'output che restituiremo è un oggetto JSON:


'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
const port = process.env.PORT || 8080;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.post('/ajax/test', function(req, res) {
    var test = req.body.test;
    res.json({output: test});
});

app.listen(port);

A questo punto il codice jQuery è semplice:


$.post( "/ajax/test", { test: "ok" }, function(response) {
   console.log( response.output ); // "ok"
});

Commenti