4

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 :)

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
nameless
  • 1,483
  • 5
  • 32
  • 78

6 Answers6

7

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: 'xxx@example.com' });

(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:

rsp
  • 107,747
  • 29
  • 201
  • 177
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: 'howareyou@xx.com' })

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

Chang
  • 1,658
  • 1
  • 17
  • 23
  • and then I can just access that `email` variable in the same js-file that I have my express in? – nameless Jul 14 '17 at 15:07
  • @nameless exactly, but make sure the url is the same both in front-end and back-end – Chang Jul 14 '17 at 15:08
  • 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? – nameless Jul 14 '17 at 15:09
  • @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:) – Chang Jul 14 '17 at 15:10
2

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!"

searsaw
  • 3,492
  • 24
  • 31
0

in server.js add this :

app.post('/searching', function(req, res){
 //do something with req
});

and in script.js :

$.ajax({
            type: "POST",
            url: "/searching",
            data: { mail: mail },
            success: function(data) {
            },
            error: function(jqXHR, textStatus, err) {
                alert('text status '+textStatus+', err '+err)
            }
        });
Mustapha Larhrouch
  • 3,373
  • 3
  • 14
  • 28
0

You need a few more things to actually be able to parse the body. Add this to your server.js file.

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

You need to specify a valid URL. Since you are listening on 3000. You also need to specify a route on your server as an endpoint.

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

Now you need to add a route on your server. You can do so by adding this to your server.js file after all of the app.use calls

app.post("/", function(req, res){
    // your logic here
    res.send("I am sending something back!");

})
ThomasK
  • 300
  • 1
  • 8
0

First of all you nedd to create a route for the Mail

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

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


var app = express();
var router=app.Router();  
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');


//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // Parse request body 


app.use(express.static(path.join(__dirname, 'public')));

// Route to check Email
router.post('/CheckEmail',(req,res)=>{
     var email=req.body.mail;   // Get email here
})

app.listen(process.env.port || 3000,()=>{
   console.log('server is running');
})

Ajax

$.ajax({
            type: "POST",
            url: "/CheckEmail",  // post route name here
            data: { mail: mail },
            success: function(data) {
            },
            error: function(jqXHR, textStatus, err) {
                alert('text status '+textStatus+', err '+err)
            }
        });
Ghanshyam Singh
  • 1,361
  • 2
  • 15
  • 27