Node.js send data to backend with AJAX

14,029

Solution 1

Note: This was written before the question was updated with the code so the field names and port numbers that I used here as examples may need to be updated with the correct values.

Client-side code - example with jQuery:

$.post('/email', { address: '[email protected]' });

(this can take optional callbacks and it returns a promise that can be used to add a success/error handler)

Server-side code - example with Express:

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

const dir = path.join(__dirname, 'public');

const app = express();

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

app.post('/email', (req, res) => {
  // you have address available in req.body:
  console.log(req.body.address);
  // always send a response:
  res.json({ ok: true });
});

app.use(express.static(dir));

app.listen(4443, () => console.log('Listening on http://localhost:4443/'));

This assumes that your static files (HTML, client-side JavaScript, CSS) are in the public directory relative to your server.js file.

See this for background on the JSON/form-encoding issue:

See this for background on serving static files:

Solution 2

That's actually quite simple to implement in Express.JS with the basic router:

I'm gonna give you the minified code snippets to help you get sense of how it works across browser and server.

in Front-End, you basically just want to "post" an email address to the backend:

$.post('/email', { email: '[email protected]' })

and in Back-End(Express.JS), you should implement the basic router:

var express = require('express');
var app = express();

// use: app.METHOD(PATH, HANDLER)
app.post('/email/', function(req, res) {
    var email = req.body.email
})

Read more here: http://expressjs.com/en/guide/routing.html

Solution 3

First, you need a valid route to hit when the server is running. You can do this in server.js through express.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(express.static('public'));

app.post('/mail', function(req, res) {
  var body = req.body;

  console.log('email', body.email);

  res.json({ message: 'I got the email!' });
});

var server = app.listen(3000);

Notice I have brought in an express middleware that will parse the body for JSON and make it available on the req object under req.body. You will need to install this dependency with npm install --save body-parser.

Then you need to send a POST request to that URL from the front-end.

$.ajax({
    type: "POST",
    url: "/mail",
    data: { mail: mail },
    success: function(data) {
      console.log('message', data.message);
    },
    error: function(jqXHR, textStatus, err) {
        alert('text status '+textStatus+', err '+err)
    }
});

Now, if you submit an email, you should see a log in your terminal that shows the email and a log in your developer console in the browser that shows the message "I got the email!"

Share:
14,029
nameless
Author by

nameless

Updated on June 04, 2022

Comments

  • nameless
    nameless almost 2 years

    I'm quite new to AJAX, so sorry for potential missunderstandings, but I'm not completely through that thing.

    I'm trying a simple thing. I have a server.js file, which is my backend basically. Then I have a index.html and a script.js. That's all, so a very basic setup. Now, on my script.js, I'm getting some data (a mail address). Now I want to send that data to my backend (into the server.js) to work with it there. How can I do this?

    I found some posts already about AJAX with node.js, but I don't get it, especially not where to receive it in my backend. I'm using express for the server by the way.

    What I have in my script.js is:

    $.ajax({
                type: "POST",
                url: "server.js",
                data: { mail: mail },
                success: function(data) {
                },
                error: function(jqXHR, textStatus, err) {
                    alert('text status '+textStatus+', err '+err)
                }
            });
    

    Right so far? How can I now receive the information in my server.js?

    There's not much in so far, just:

    var express = require('express');
    
    var app = express();
    var server = app.listen(3000);
    
    app.use(express.static('public'));
    

    Thanks for any help :)

  • nameless
    nameless almost 7 years
    and then I can just access that email variable in the same js-file that I have my express in?
  • Chang
    Chang almost 7 years
    @nameless exactly, but make sure the url is the same both in front-end and back-end
  • nameless
    nameless almost 7 years
    okay, but there doesn't have to be a file like email.js, I can just use whatever name I want, it just have to be the same?
  • Chang
    Chang almost 7 years
    @nameless yes, but if your program goes larger and larger, you may want to design a good modular pattern to make the whole project more managable. for example, a file "route.js" which is used to handle the routing issue:)