Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从angular 4应用程序接收时,快速接收空请求正文_Javascript_Angularjs_Node.js_Angular_Express - Fatal编程技术网

Javascript 从angular 4应用程序接收时,快速接收空请求正文

Javascript 从angular 4应用程序接收时,快速接收空请求正文,javascript,angularjs,node.js,angular,express,Javascript,Angularjs,Node.js,Angular,Express,根据我的快速路线中的req.body,发送的请求正文为空 我的主节点文件如下所示- var express = require('express'); var bluebird = require('bluebird') const bodyParser = require('body-parser'); const cors = require('cors'); /*initializations*/ global.mongoose = require('mongoose'); mongoo

根据我的快速路线中的req.body,发送的请求正文为空

我的主节点文件如下所示-

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)})
});
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       

  })
});
angular 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;
      }
  });
}
注册(用户:用户):可观察{
返回this.http.post(this.signup\uURL,JSON.stringify(user),
{
headers:new-HttpHeaders().set('Accept',“application/json;q=0.9,*/*;q=0.8”).set('Content-Type',“x-www-form-encoded”)
})
.map((响应:响应)=>{
如果(答复){
if(response.json()&&response.json().token&&response.json().user&&response.json().expires){
this.setSession(response.json());
返回true;
}
否则{
返回false;
}  
}
否则{
返回false;
}
});
}
我确信Angular 4应用程序正在向服务器发送正确的数据,并且它的chromes网络请求主体不是空的

我尝试了以下链接,但都没有成功


还尝试了postman,结果相同-这意味着问题来自express服务器,而不是客户端。

无需对发布的数据进行字符串化,
正文解析器
中间件将负责将数据解析为对象:

return this.http.post(this.signup_url, user, { ... }).map( ... );
还有一件事,在post处理程序中,您可能希望使用方法,而不是因为您已经创建了模型实例,请记住,
.save()
方法在模型实例上可用,而
.create()
直接从模型调用,并将对象作为第一个参数

示例使用
.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 });
    })
});
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 });
    });
});
示例使用
.create()
方法:

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 });
    })
});
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 });
    });
});

Yh我将尝试不使用JSON.stringify。关于保存与创建。代码的执行根本就没有达到这一点。它在bcrypt.hashsync处中断。尝试添加
console.log(req.body)
以查看是否首先提交了数据