czioutas
czioutas

Reputation: 1068

AJAX post to Express returns no data to req.query (yes there is the same q but nothing works)

this is my set up. However when I send data through the ajax the body is empty. On chrome under network I see the post and the content, with a correct payload:

request

{"EventName":"asd","PrivacyLevel":1,"TypeInt":1,"ExpectedDate":"asd","Desc":"asd","Down":0,"Up":0,"PostCode":"","Address":"","ID":""}

Most people say its the body parser, I have placed the parsers above the app.use(app.router) I dont know if it creates any conflict with express.json() but when I commented it out it didnt make any difference.

   app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());
    app.use(express.cookieParser('secret'));
    app.use(express.session({ secret: 'randomstring' }));
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));

$.ajax({
    url: window.location.origin + '/registerEvent',
    contentType: 'application/json: charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(Event.toJSONString()),
    cache: false,
    timeout: 5000,
    async: false,
    success: function (result) {
        success = true;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('error ' + textStatus + " " + errorThrown);
        success = false;
    }
});

exports.registerEvent = function (req, res) {
    if (req.session.lastPage === '/index' && req.xhr) {
        console.log(req);
        console.log(req.body);
        console.log('body: ' + JSON.stringify(req.body));

        var test = req.query.EventName;

Upvotes: 1

Views: 2093

Answers (4)

JacobRossDev
JacobRossDev

Reputation: 413

I copied the code generated by Postman and it worked for me.

Instead of using my normal code

$.ajax({
  url: 'http://localhost:3001/api/v1/signup',
  data: {
    first_name: 'jacob',
    last_name: 'ross',
    username: 'username',
    emailAddress: '[email protected]',
    password: 'somepassword'
  },
  type: 'POST',
  contentType: 'application/json: charset=utf-8', // caused CORS issue
  success: function(d){
    console.log(d);
  }
})

I used this from Postman which worked just fine, and was able to access the params with req.query.

var settings = {
  "url": "http://localhost:3001/api/v1/[email protected]&password=123456789&first_name=jacob&last_name=ross&username=jacobrossdev",
  "method": "POST",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});

Upvotes: 0

AzizAhmad
AzizAhmad

Reputation: 647

in my case I soveld it by this :

res.header("Access-Control-Allow-Origin", "*");

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 146134

The data will be available in req.body (the parsed HTTP request body from the AJAX JSON) not req.query (the URL query string).

In your jquery ajax code, use contentType: 'application/json' and that should get it doing the kind of POST request you want.

Upvotes: 4

Hector Correa
Hector Correa

Reputation: 26690

I think you found a bug in Connect (the middleware that Express uses to parse the body). The code for the bodyParser uses a regular expression to match the "application/json" content type that fails when the "charset=utf-8" is appended to it.

Here is the Connect.js code that I am talking about: https://github.com/senchalabs/connect/blob/master/lib/middleware/json.js#L54

The RegEx that Connect is using is

/^application\/([\w!#\$%&\*`\-\.\^~]*\+)?json$/i

If you run the following code Node you'll see that the one with "charset=utf-8" fails the test:

regex = /^application\/([\w!#\$%&\*`\-\.\^~]*\+)?json$/i
regex.test("application/json") // returns true
regex.test("application/json: charset=utf-8") // returns false

Upvotes: 2

Related Questions