NodeJS错误 - 发送后无法设置标头

时间:2016-05-16 10:14:39

标签: javascript node.js express pug

我在NodeJS方面相对较新,我从本教程系列中学习。

https://www.youtube.com/watch?v=49sWXJPk10Q&list=PLO-hrPk0zuI18xlF_480s6UiaGD7hBqJa&index=15

在此特定视频中,我在提交表单后遇到了一些错误。我有两个疑问,在这个网站搜索没有得到一个明确的答案。我希望你能给我更多的清晰度。

1.在users.js中,在第32行中它表示未定义的profileimage,尽管我有一个名为profileimage的文件字段。

2.如果该行改为req.body.profileimage,那不会产生错误,但我认为这仍然是错误的。提交表单时,nodeJS抛出错误

错误'在发送标题后无法设置标题'

我尝试阅读其他类似的问题,但我无法将其与我的程序相关联(因为我没有明确地在程序中设置任何标题)。请更深入地了解这两个问题。

var express = require('express');
var router = express.Router();


//var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register', {
      'title': "Register"
  });
});

router.get('/login', function(req, res, next) {
  res.render('login', {
      'title': "Login"
  });
});

router.post('/register', function(req, res, next) {
    //Get form values
    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.password;
    var cpassword  = req.body.cpassword;


    //Check for image field
    if(req.files.profileimage) {
        console.log('Uploading File...');

        //File Info
        var profileImageOriginalName = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImageMime = req.files.profileimage.mimetype;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt = req.files.profileimage.extension;
        var profileImageSize = req.files.profileimage.size;

    }
    else {
        var profileImageName = 'default.png';
    }

    //form validation
    req.checkBody('name','Name field is required').notEmpty();
    req.checkBody('email','Email field is required').notEmpty();
    req.checkBody('email','Enter a valid Email').isEmail();
    req.checkBody('password','Password field is required').notEmpty();
    req.checkBody('cpassword','Passwords fields do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors) {
        res.render('register', {
            errors: errors,
            name: name,
            email: email,
            password: password
        });
    }
    else {
        var newUser = new User({
            name: name,
            email: email,
            password: password,
            profileImage: profileImageName
        });
    }

*/
    //Success Message
    req.flash('success','You are now registered and may log in');

    res.location('/');
    res.redirect('/');

});

module.exports = router;

register.jade

extends layout

block content
  ul.errors
    if errors
      each error, i in errors
       li.alert.alert-danger #{error.msg}
  form.form-signin(method='post',action='/users/register',enctype='multipart/form-data')
      h2.form-signin-heading.text-center Register
      label.sr-only(for='inputName') Name
      input#inputName.form-control(name='name' type='text', placeholder='Name', autofocus='')
      label.sr-only(for='inputEmail') Email address
      input#inputEmail.form-control(name='email' type='email', placeholder='Email address')
      label.sr-only(for='inputPassword') Password
      input#inputPassword.form-control(name='password' type='password', placeholder='Password')
      label.sr-only(for='inputCPassword') Confirm Password
      input#inputCPassword.form-control(name='cpassword' type='password', placeholder='Confirm Password')
      label.sr-only(for='inputProfile') Profile Image
      input#inputProfile.form-control(name='profileimage' type='file')
      button.btn.btn-lg.btn-primary.btn-block(type='submit') Register

更详细的错误报告

POST /users/register 500 91.651 ms - 2704<br>
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (C:\Dev\nodeauth\node_modules\express\lib\response.
js:718:10)
    at ServerResponse.send (C:\Dev\nodeauth\node_modules\express\lib\response.js
:163:12)
    at done (C:\Dev\nodeauth\node_modules\express\lib\response.js:957:10)
    at Object.exports.renderFile (C:\Dev\nodeauth\node_modules\jade\lib\index.js
:374:12)
    at View.exports.__express [as engine] (C:\Dev\nodeauth\node_modules\jade\lib
\index.js:417:11)
    at View.render (C:\Dev\nodeauth\node_modules\express\lib\view.js:126:8)
    at tryRender (C:\Dev\nodeauth\node_modules\express\lib\application.js:639:10
)
    at EventEmitter.render (C:\Dev\nodeauth\node_modules\express\lib\application
.js:591:3)
    at ServerResponse.render (C:\Dev\nodeauth\node_modules\express\lib\response.
js:961:7)
    at C:\Dev\nodeauth\app.js:104:7
    at Layer.handle_error (C:\Dev\nodeauth\node_modules\express\lib\router\layer
.js:71:5)
    at trim_prefix (C:\Dev\nodeauth\node_modules\express\lib\router\index.js:310
:13)
    at C:\Dev\nodeauth\node_modules\express\lib\router\index.js:280:7
    at Function.process_params (C:\Dev\nodeauth\node_modules\express\lib\router\
index.js:330:12)
    at IncomingMessage.next (C:\Dev\nodeauth\node_modules\express\lib\router\ind
ex.js:271:10)
    at done (C:\Dev\nodeauth\node_modules\express\lib\response.js:956:25)
    at tryRender (C:\Dev\nodeauth\node_modules\express\lib\application.js:641:5)

    at EventEmitter.render (C:\Dev\nodeauth\node_modules\express\lib\application
.js:591:3)
    at ServerResponse.render (C:\Dev\nodeauth\node_modules\express\lib\response.
js:961:7)
    at C:\Dev\nodeauth\app.js:93:9
    at Layer.handle_error (C:\Dev\nodeauth\node_modules\express\lib\router\layer
.js:71:5)

1 个答案:

答案 0 :(得分:2)

您需要移动此代码:

//Success Message
req.flash('success','You are now registered and may log in');

res.location('/');
res.redirect('/');

它应该在条件内:

else {
        var newUser = new User({
            name: name,
            email: email,
            password: password,
            profileImage: profileImageName
        });
        //Success Message
        req.flash('success','You are now registered and may log in');

        res.location('/');
        res.redirect('/');
    }

如果你在外面发生了什么会发生错误就是这个。首先你的if语句触发:

if(errors) {
    res.render('register', {
        errors: errors,
        name: name,
        email: email,
        password: password
    });
}

调用res.render时,响应完成并发送标头。但是:由于条件Express之外的res.redirectres.location尝试运行它。这就是您收到错误消息的原因。

正如您对问题的评论中指出的那样,您可以阅读更多here