How do I access the data in a POST request in express?

时间:2015-07-31 20:21:45

标签: javascript post express client server

Here's my client side code:

  $.post("/audio",
    {
      type: 'instrumental',
      name: 'Instrumental_30SecondsToMars_TheKill'
    },
    function(data, status) {
      alert("Data: " + data + "\nStatus: " + status);
    });

And here's my server side code:

app.post('/audio', function (req, res) {
  console.log(req.body);
});

How do I access the type and name that I sent in the post from within the server side function?

It's definitely being called as the server is console logging.

2 个答案:

答案 0 :(得分:0)

You need to use the bodyparser middleware:

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

and then

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

答案 1 :(得分:0)

You need to use a parsing module like body-parser

Use like this:

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

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/audio', function (req, res) {
  console.log(req.body); // <-- now has req.body.type, req.body.name
});