Joseph
Joseph

Reputation: 1966

Send a variable or array from javaScript to node js with ajax

I wanna do this: Grab some data from my dom with javascript, save them to a variable and then send that to node js, grab that with express and finally save that into database. client side javaScript:

var tags = ["apple","orange","green"];

$.ajax({
        type: "POST",
        url: '/posts',
        data: { tags : tags },
        success: function(data)
        {
            alert("success!");
        }
    });

now I am trying to grab that data with express like this:

My server code:

/***** CREATE A POST *****/
app.post('/posts', function (req, res) {

  //code

  var tags = req.body.tags;

  // create that post

});

But that doesn't work correct. what is the problem?

Upvotes: 0

Views: 282

Answers (2)

Robson Pontes
Robson Pontes

Reputation: 9

You must input host and port information in the request, like this:

$.ajax({ type: "POST", url: 'http://localhost:3000/posts', data: { tags : tags }, success: function(data) { alert("success!"); } });

Upvotes: 0

deniscapp
deniscapp

Reputation: 820

The only thing you need to do, is to use body-parser before your "post" route, otherwise it won't work. The order of the middleware matters.

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

app.post('/posts', function (req, res) {

  //code

  var tags = req.body.tags;

  // create that post

});

Upvotes: 1

Related Questions