Access Data Sent to NodeJS Server via Ajax Post

后端 未结 1 1392
暗喜
暗喜 2020-12-31 21:51

How do I access the data sent to a Nodejs Server via Ajax POST?

    //Client
$.ajax( {
    url: \'/getExp\',
    data: \'Idk Whats Rc\',
    type: \'POST\',
         


        
相关标签:
1条回答
  • 2020-12-31 22:20

    Express 4.x:

    Express 4 no longer contains Connect as a dependency, which means you will need to install the body parsing module separately.

    The parser middleware can be found at its own GitHub repository here. It can be installed like so:

    npm install body-parser
    

    For form data, this is how the middleware would be used:

    var bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded());
    

    For Express 3.x and before:

    You need to use the bodyParser() middleware in Express which parses the raw body of your HTTP request. The middleware then populates req.body.

    app.use(express.bodyParser());
    app.post('/path', function(req, res) {
      console.log(req.body);
    });
    

    You might want to pass an object instead of a string to your POST request because what you currently have will come out like this:

    { 'Idk Whats Rc': '' }
    

    Using code somewhat like this:

    $.ajax({
      url: '/getExp',
      data: { str: 'Idk Whats Rc' },
      type: 'POST',
    });
    

    Will get you this:

    { str: 'Idk Whats Rc' }
    
    0 讨论(0)
提交回复
热议问题