问题
I am using angular 8 as front end framework, I was trying to do a http post request to send login details(object), which is not null or undefined, but on server side the request body of post is undefined. I am using nodejs on server side.
client side-> service.ts:
register( details:any){
const url="http://localhost:4000/register";
console.log(details);
return this.http.post(url,details,httpOptions);
}
server side ->app.js:
app.post('/register',cors(),function(req,res){
console.log(req.body);
})
The req.body must contain an object which is same as details in service.ts but getting undefined
回答1:
Add body parser middleware before declaring the route:
const express = require('express');
// ...
app.use(express.json());
//...
app.post('/register', cors(), function(req,res) {
console.log(req.body);
})
回答2:
There is no body without body-parser.first install body-parser
npm install body-parser
Then use it in express 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 }))
// parse application/json
app.use(bodyParser.json())
来源:https://stackoverflow.com/questions/57303416/i-made-a-http-post-request-in-client-sideangular-8-but-getting-undefined-in-se