0

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?

3
  • can you see if you are correctly going to the /posts POST call, and try doing console.log(req.body.tags), and see if you are successfully receiving the data Commented Jan 7, 2017 at 14:29
  • have you used bodyParser middleware Commented Jan 7, 2017 at 14:31
  • Yes I use bodyParser. Do I need to install any esp package in order to use ajax? Commented Jan 7, 2017 at 17:04

2 Answers 2

1

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

});
Sign up to request clarification or add additional context in comments.

Comments

0

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!"); } });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.