简体   繁体   English

从角度4应用程序接收时表达接收空请求正文

[英]express receiving empty request body when receiving from angular 4 app

The body of the request being sent is empty according to req.body in my express route. 根据我的快递路线中的req.body,正在发送的请求的正文是空的。

My main node file is as follows - 我的主节点文件如下 -

var express = require('express');
var bluebird = require('bluebird')
const bodyParser = require('body-parser');
const cors = require('cors');

/*initializations*/
global.mongoose = require('mongoose');
mongoose.Promise = bluebird
global.app = express();
global.config = require('./config/config');
global.jwt = require('jsonwebtoken');
app.use(bodyParser.json({ type: 'application/json' }))
app.use(bodyParser.urlencoded({ extended: true }));//accept strings, arrays   and any other type as values
app.disable('x-powered-by');

require('./routes/auth.routes');

//DB connection
app.listen(config.port, function(){
 console.log("Express started on " +config.base_url +' in '+config.env +' environment. Press Ctrl + C to terminate');
 mongoose.connect(config.db.uri, config.db.options)
 .then(()=> { console.log(`Succesfully Connected to the Mongodb Database  at URL : `+config.db.uri)})
 .catch((error)=> { console.log(error)})
});

The auth.routes file has the signup route and this is where the req.body is empty but it does not hit the if statement that checks, but when i console.log(re.body), it gives me that - {} auth.routes文件有注册路由,这是req.body是空的,但它没有点击检查的if语句,但是当我在console.log(re.body)时,它给了我 - {}

app.post('/signup', function(req,res,next){

if (!req.body||req.body=={}){
    return res.status(400).send("Bad Request")
}

var user = new User(req.body);

user.password = bcrypt.hashSync(req.body.password, 10);

User.create(user, function(err,new_user){
    if (err) {
        console.log('A Big Error');
        return res.status(500).send("There was a problem registering the user.")
    }

   //success code       

  })
});

And the request from the angular 4 app is 而角4应用程序的请求是

signup(user:User):Observable<boolean>{

return this.http.post(this.signup_url,JSON.stringify(user), 
  {
    headers: new HttpHeaders().set('Accept', "application/json;q=0.9,*/*;q=0.8").set('Content-Type', "x-www-form-encoded")
  })
  .map((response: Response) => {
      if(response){
        if(response.json() && response.json().token&&response.json().user&&response.json().expires){
          this.setSession(response.json());
          return true;
        }
        else{
           return false;
        }  
      }
      else{
          return false;
      }
  });
}

I am certain the Angular 4 app is sending the right data to the server and that its not empty - checked chromes network request body. 我确信Angular 4应用程序正在向服务器发送正确的数据并且它不是空的 - 检查了chromes网络请求正文。

I have tried the following links but none worked. 我尝试过以下链接但没有效果。

Express app empty request body with custom content type headers 具有自定义内容类型标题的Express app空请求正文

Express receiving empty object 快递接收空对象

Node.js: Receiving empty body when submitting form . Node.js:提交表单时接收空体

Also tried with postman and the result is the same - which means the problem is from the express server and not the client side. 也尝试使用邮递员,结果是相同的 - 这意味着问题来自快递服务器而不是客户端。

There is no need to stringify the posted data, the body-parser middleware will be responsible for parsing the data into object: 没有必要对发布的数据进行字符串化, body-parser中间件将负责将数据解析为对象:

return this.http.post(this.signup_url, user, { ... }).map( ... );

One other thing, In the post handler, you might want to use .save() method instead of .create() because you already create a model instance, Remember that the .save() method is available on the model instance, while the .create() is called directly from the Model and takes the object as a first parameter 另一件事,在post处理程序中,您可能希望使用.save()方法而不是.create(),因为您已经创建了一个模型实例,请记住.save()方法在模型实例上可用,而.create()直接从Model调用,并将该对象作为第一个参数

Example with .save() method: .save()方法示例

app.post('/signup', function(req,res,next) {

    if (!req.body){
        return res.status(400).send("Bad Request");
    }

    var user = new User(req.body);

    var salt = bcrypt.genSaltSync(saltRounds);
    user.password = bcrypt.hashSync(req.body.password, salt);

    user.save(function( err ) {
        if (err) {
            console.log('A Big Error');
            return res.status(500).send("There was a problem registering the user.");
        }

        //success code       
        res.json({ success: true });
    })
});

Example with .create() method: 使用.create()方法的示例

router.post('/signup', function(req,res,next){

    if (!req.body){
        return res.status(400).send("Bad Request")
    }

    var salt = bcrypt.genSaltSync(saltRounds);
    req.body.password = bcrypt.hashSync(req.body.password, salt);

    User.create ( req.body, function( err,  new_user) {
        if (err) {
            console.log('A Big Error');
            return res.status(500).send("There was a problem registering the user.")
        }

        //success code       
        res.json({ success: true });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM