req.body没有返回提交的数据

时间:2017-10-15 16:30:58

标签: node.js angular express mongoose

我试图学习MEAN堆栈,我面临一个问题。我开发了小型Express应用程序。但这个我无法弄清楚。

我使用Angular Http Service发布表单数据。

使用post方法发布数据的服务代码。

createUser(user: User): Observable<User> {
const submittedUser = JSON.stringify(user);
console.log("submitted:", submittedUser);
const headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({headers: headers});
return this.http.post('http://localhost:3000/user/create', submittedUser, options)
  .map((response: Response) =>  {response.json()})
  .catch((error:Response) => Observable.throw(error.json()));

}

在服务器端,我有app.js和一个路由器文件。

'use strict';

var express = require('express');
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var userRoutes = require('./routes/userRoutes');

var app = express();
mongoose.connect('mongodb://localhost/go-social');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

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

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
    next();
});

app.use('/user', userRoutes);

app.use(function(req, res, next) {
    return res.render('error');
});

app.listen(3000, function() {
    console.log("App listening on port 3000");
})

这是路由器文件。 userRoutes.js

enter var express = require('express');
var router = express.Router();
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var User = require('../models/user');
router.post('/create', function (req, res) {

    console.log(req.body);
    var user = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        password: req.body.password
    });
    user.save(function(err, result) {
        if(err) next(err);
        res.status(201).json({
            message: "Your account has been created successfully",
            obj: result
        });
    });
});

当我使用Postman时,它可以工作,但它不能与Http服务一起使用。我在控制台中将req.body作为提交对象的对象。

{ '{"firstName":"Myname","lastName":"sadf","email":"abc@gmail.com","password":"awe"}': '' }

1 个答案:

答案 0 :(得分:3)

更改

发件人

const headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' })

const headers = new Headers ({  'Content-Type': 'application/json' })