简体   繁体   中英

node.js req.body empty when sending from java with httpPost

When I'm trying to send some json to my node.js server req.body is empty and I have no idea why. The headers I'm sending are received.

This is the java code:

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(json, "UTF8");

        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("test", "test");

        HttpResponse httpResponse = httpClient.execute(httpPost);

And this is the node.js code:

exports.checkMail = function(req, res) {
    var user = req.body;
    var header = req.headers;
    var email = user.email;
    db.collection('users', function(err, collection) {
        collection.findOne({'email':email}, function(err, item) {
            if (item) {
                res.send({'error':0, 'message':'email available'});
            } else {
                res.send({'error':4, 'message':'email already taken'});
            }
        });
    });
};

Any ideas of what I might be missing?

EDIT:

Sorry forgot to mention. I'm using Express. And the json i'm sending is:

{"email":"email@email.com"}

What I get from req.body is just: {}

EDIT2:

app.js

    var express = require('express'),
        post = require('./routes/posts'),
        user = require('./routes/user');

    var app = express();

    app.configure(function () {
        app.use(express.logger('dev'));
        app.use(express.bodyParser());
        //app.use(express.json());
        //app.use(express.urlencoded());
    });

    app.get('/auth',            user.login); 
    app.post('/auth',           user.addUser);
    app.put('/auth/:id',        user.updateUser); 
    app.post('/checkmail',      user.checkMail);  
    app.post('/reset',          user.resetPassword); 

    app.listen(8080);
    console.log('Listening on port 8080...');

Probably too late to answer, but if anybody has this same problem this is what worked for me:

//It is important that if we are sending a Content-Type application/json, the entity has to receive a json 
JSONObject js = new JSONObject();
js.put("key", value);
String url = "http://mylocalhosturl";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(js.toString(), HTTP.UTF_8);

//Setting the content type is very important
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);

//Execute and get the response.
HttpResponse response = httpClient.execute(httpPost);

Hope this helps to someone.

You app.js file should have these middleares included;

var express = require('express');

var app = express();

// app configs; include these;
app.use(express.json());
app.use(express.urlencoded());

// other configurations

app.use(app.router)

// ...

Hope this helps.

I would first determine if the problem is client side or server side. Your client code looks ok to me, so I would try hitting your server with a simple curl command.

For example:

curl -k -i -H 'Accept: application/json' -H 'Content-type: application/json' -X POST -d '<YOUR POST BODY>' 'http://yourhost/yourendpoint'

This will help determine if it's a purely server side issue, which I suspect in this case it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM