Hongbo Miao Hongbo Miao - 3 months ago 14
HTTP Question

req.body is empty when when header is { 'Authorization': 'Bearer ' + token }

I am using Angular 2 as front end. I tried to send an Object

{ test: 'Hi' }
.

When my http header is like this:

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });


I can get the content I sent on the server side using
req.body
.

However, when my http header is like this:

let headers = new Headers({ 'Authorization': 'Bearer ' + token });
let options = new RequestOptions({ headers: headers });


When I use
req.body
again, I got an empty Object
{}
.

My server is using Express.js, and my bodyParser is like this:

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


How can I do it correctly? Thanks

Answer

You should send both headers to express:

let headers = new Headers({ 
  'Content-Type': 'application/json', 
  'Authorization': 'Bearer ....' 
}); 
Comments