发送后无法设置标题 - express.js - angular 4

时间:2017-09-20 10:22:53

标签: node.js angular express

./模型/ user.js的

var mongoose = require('mongoose');
var validator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;

const schema = new Schema({
    firstName:{ type: String, required: true },
    lastName: {type: String, required: true},
    password: {type: String, required: true},
    email: {type: String, required: true, unique: true },
    transactions: [{type: Schema.Types.ObjectId, ref: 'Transaction'}]  
});

schema.plugin(validator);

module.exports = mongoose.model('User', schema);

app.js

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

var appRoutes = require('./routes/app');
var userRoutes= require('./routes/user');

var app = express();
mongoose.connect('localhost:27017/remake');

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
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('/', appRoutes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    return res.render('index');
});


module.exports = app;

” ./路由/ item.js'

var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/user');
const bcrypt = require('bcryptjs');

router.post('/', function(req, res, next) {
    User.findOne({email: req.body.email}, (err, user) => {
        if(err){
            return res.status(500).json({
                title: 'An error has occured',
                error: err
            });
        }
        if(user){
            return res.status(401).json({
                title: 'Email already taken!',
                error: {message: 'Email already taken!'}
            });
        }
    });
    const user = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email   : req.body.email,
        password: bcrypt.hashSync(req.body.password, 10)
    });
    user.save( (err, result) => {
        if(err){
            return res.status(500).json({
                title: 'An error has occured',
                error: err
            });
        }
        res.status(201).json({
            title: 'User created!',
            obj: result
        });
    });

});


module.exports = router;

每次创建用户都没关系 - 但是一旦用同一封电子邮件创建用户,就会抛出此错误。

> _http_outgoing.js:504
>     throw new Error('Can\'t set headers after they are sent.');
>     ^
> 
> Error: Can't set headers after they are sent.
>     at validateHeader (_http_outgoing.js:504:11)
>     at ServerResponse.setHeader (_http_outgoing.js:511:3)
>     at ServerResponse.header (/Users/sean/Angular/appdev-remake/node_modules/express/lib/response.js:719:10)
>     at ServerResponse.send (/Users/sean/Angular/appdev-remake/node_modules/express/lib/response.js:164:12)
>     at ServerResponse.json (/Users/sean/Angular/appdev-remake/node_modules/express/lib/response.js:250:15)
>     at Query.User.findOne (/Users/sean/Angular/appdev-remake/routes/user.js:16:36)
>     at /Users/sean/Angular/appdev-remake/node_modules/kareem/index.js:177:19
>     at /Users/sean/Angular/appdev-remake/node_modules/kareem/index.js:109:16
>     at _combinedTickCallback (internal/process/next_tick.js:95:7)
>     at process._tickCallback (internal/process/next_tick.js:161:9)

我已经为我能找到的每个实例添加了return语句 - 这是一个express / mongo错误还是我的代码有问题。我之前编写过这个REST API并将它们放在一边,它们实际上是相同的但是这个不起作用。

1 个答案:

答案 0 :(得分:3)

您在user.save

的回调范围之外呼叫User.findOne

见下文 - 我已在User.findOne回调中创建了一个用户:

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

    User.findOne({email: req.body.email}, (err, user) => {

        if(err){
            return res.status(500).json({
                title: 'An error has occured',
                error: err
            });
        }
        if(user){
            return res.status(401).json({
                title: 'Email already taken!',
                error: {message: 'Email already taken!'}
            });
        }

        //this is inside the callback
        const user = new User({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email   : req.body.email,
            password: bcrypt.hashSync(req.body.password, 10)
        });

        user.save( (err, result) => {
            if(err){
                return res.status(500).json({
                    title: 'An error has occured',
                    error: err
                });
            }
                return res.status(201).json({
                    title: 'User created!',
                    obj: result
                });
        });
    });
});

在您的代码中,return实际上被调用了两次,因此错误