Node.js: richieste AJAX GET con jQuery ed Express

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

Node.js di Gabriele Romanato

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

In Express i parametri GET vengono memorizzati nell'oggetto query 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.get('/ajax/test', function(req, res) {
    var test = req.query.test;
    res.json({output: test});
});

app.listen(port);

A questo punto il codice jQuery è semplice:


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

Commenti