1

Here is an example of my data as per console.log(payload):

Object {title: "test post", message: "some message", image: "cat.jpg"}

However, this is what shows up in my mongo collection:

{
    "_id": "5684609f8d6ff91e159cef6d",
    "created_at": "2015-12-30T22:54:23.266Z",
    "updated_at": "2015-12-30T22:54:23.266Z",
    "__v": 0
  }

Here is the code:

console.log(payload); // what this returns is posted above!
var request = new XMLHttpRequest();
        request.open('POST', 'http://localhost:3000/api/v1/posts', true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.send(payload);

Can someone help me?

Here is the relevant code from server.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fluxible-posts');

var Post = require('./database/postModel');


// routes
var router = express.Router();
server.use('/api/v1/', router); 

router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route 
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

router.route('/posts')
    .post(function(req,res) {
        var post = new Post();
        post.title = req.body.title;
        post.message = req.body.message;
        post.image = req.body.image;

        post.save(function(err) {
            if(err) {
                res.send(err);
            }
            res.json({ message : 'New post created' });
        });
    })
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err)
                res.send(err);

            res.json(posts);
        });
    });

router.route('/posts/:post_id')

    // get the post with that id
    .get(function(req, res) {
        Post.findById(req.params.post_id, function(err, post) {
            if (err)
                res.send(err);
            res.json(post);
        });
    })

    // update the post with this id
    .put(function(req, res) {
        Post.findById(req.params.post_id, function(err, post) {

            if (err)
                res.send(err);

            post.name = req.body.name;
            post.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Post updated!' });
            });

        });
    })

    // delete the post with this id
    .delete(function(req, res) {
        Post.remove({
            _id: req.params.post_id
        }, function(err, post) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });
user1354934
  • 8,139
  • 15
  • 50
  • 80

2 Answers2

1

In case if you add request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); you should send payload not in object from but as POST data string like

title=test%20post&message=some%20message&image=cat.jpg

You can use serialize function from Query-string encoding of a Javascript Object

Update:

As I see you didn't added POST data parser middleware to your router so your req.body is undefined. For Content-Type: application/x-www-form-urlencoded you should use body-parser module.

You can install it with npm install body-parser and change your server code to

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

var router = express.Router();
router.use(bodyParser.urlencoded({ extended: true }));

server.use('/api/v1/', router); 

First part of my comment still valid.

Update 2:

Alternatively you can use Content-type: application/json. In this case you need to update your client code should look like:

var payload = {test: "data"}
var request = new XMLHttpRequest(); 
request.open('POST', 'http://localhost:3005/api/v1/posts', true); 
request.setRequestHeader('Content-Type', 'application/json'); 
request.send(JSON.stringify(payload));

And server side:

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

var router = express.Router();
router.use(bodyParser.json());

server.use('/api/v1/', router);
Community
  • 1
  • 1
CrazyCrow
  • 4,125
  • 1
  • 28
  • 39
  • I've added application/json solution in case if you don't want to use additional functions on client side. – CrazyCrow Dec 30 '15 at 23:35
1

Try following code

var request = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        console.log("success : " + request.responseText);
    } else {
        //This would print if something goes wrong along with the error message
        console.log("other status : " + request.status + " : " + request.responseText);
    }
};

request.open('POST', 'http://localhost:3000/api/v1/posts', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//We need to serialize payload before sending it
request.send(JSON.stringify(payload));

You can use Chrome's network tab under developer tools to monitor the network requests sent. There you would be able to see if the body of the request was sent or not or if the headers were sent as they were set and what was the response.

See the images below

enter image description here

enter image description here

11thdimension
  • 10,333
  • 4
  • 33
  • 71