I made a http post request in client side(angular 8) but getting undefined in server side(node.js)

时光总嘲笑我的痴心妄想 提交于 2019-12-13 03:48:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!