2016-02-26 57 views
3
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var UserSchema = new Schema({ 
    tel: { 
     type: Number, 
     unique: true 
    }, 
    name: String, 
    hash_password: String, 
    created_at: Date 
}, { 
    collection: 'users' 
}); 

var User = mongoose.model('User', UserSchema); 

module.exports = User; 

login.js如何處理無法設置頁眉他們被送到

var crypto = require('crypto'); 
var express = require('express'); 
var jwt = require('jsonwebtoken'); 
var router = express.Router(); 
var User = require('../modules/user'); 
var Token = require('../modules/token'); 

router.get('/', function(req, res,next) { 
    res.render('login', { 
     title: '登錄界面' 
    }); 
    next(); 
}); 

router.post('/', function(req, res) { 
    User.findOne({ 
     tel: req.body.tel, 
    }) 
    .exec(function(err, user) { 
     var md5 = crypto.createHash('md5'), 
      password = md5.update(req.body.password) 
      .digest('hex'); 
     if (!user) { 
      return res.json({ 
       success: false, 
       message: '認證失敗,用戶名找不到' 
      }); 
     } else if (user.hash_password === password) { 
      var token = jwt.sign(user, 'whuteditor', { 
       expiresIn: "30 days" // 設置過期時間 
      }); 
      var tokenUser = new Token({ 
       token: token 
      }); 

      tokenUser.set("nickname", req.body.name); 

      tokenUser.save(function(err, token) { 
       if (err) { 
        return res.json({ 
         status: 120, 
         success: false, 
         message: "存儲出錯" 
        }); 
       } 
       console.log(token); 
      }); 
      return res.json({ 
       status: 100, 
       success: true, 
       message: 'Enjoy your token!', 
       token: token 
      }); 
      //res.end(); 
      //res.end(); 
     } else { 
      return res.json({ 
       status: 007, 
       success: false, 
       message: '沒有當前用戶' 
      }); 
     } 
    }); 
}); 

module.exports = router; 

錯誤後:

Error: Can't set headers after they are sent. 
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) 
    at ServerResponse.header (/Users/guchenghao/Atom-code/project/editor/node_modules/express/lib/response.js:718:10) 
    at ServerResponse.send (/Users/guchenghao/Atom-code/project/editor/node_modules/express/lib/response.js:163:12) 
    at ServerResponse.json (/Users/guchenghao/Atom-code/project/editor/node_modules/express/lib/response.js:249:15) 
    at ServerResponse.send (/Users/guchenghao/Atom-code/project/editor/node_modules/express/lib/response.js:151:21) 
    at /Users/guchenghao/Atom-code/project/editor/routes/login.js:40:18 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/lib/document.js:1813:19 
    at handleError (/Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:40:22) 
    at next_ (/Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:75:26) 
    at fnWrapper (/Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/hooks-fixed/hooks.js:186:18) 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/lib/model.js:287:15 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/lib/model.js:188:14 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/lib/model.js:132:9 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/mongodb/lib/collection.js:491:20 
    at /Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/mongodb/lib/collection.js:604:14 
    at handleCallback (/Users/guchenghao/Atom-code/project/editor/node_modules/mongoose/node_modules/mongodb/lib/utils.js:96:12) 

npm ERR! Darwin 15.3.0 
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start" 
npm ERR! node v4.3.0 
npm ERR! npm v2.14.12 
npm ERR! code ELIFECYCLE 
npm ERR! [email protected] start: `node ./bin/www` 
npm ERR! Exit status 1 
npm ERR! 
npm ERR! Failed at the [email protected] start script 'node ./bin/www'. 
npm ERR! This is most likely a problem with the editor package, 
npm ERR! not with npm itself. 
npm ERR! Tell the author that this fails on your system: 
npm ERR!  node ./bin/www 
npm ERR! You can get their info via: 
npm ERR!  npm owner ls editor 
npm ERR! There is likely additional logging output above. 

npm ERR! Please include the following file with any support request: 
npm ERR!  /Users/guchenghao/Atom-code/project/editor/npm-debug.log 
+1

我認爲你需要刪除get方法中的next()調用。 res.render應該是請求的結尾。 – ojf

回答

1

你打電話res.json之前,您可以檢查,如果你的頭有使用res.headersSent發送。如果已發送,請致電next()

更新: 您在.save函數中存在競態條件。

var crypto = require('crypto'); 
var express = require('express'); 
var jwt = require('jsonwebtoken'); 
var router = express.Router(); 
var User = require('../modules/user'); 
var Token = require('../modules/token'); 

router.get('/', function(req, res,next) { 
    res.render('login', { 
     title: '登錄界面' 
    }); 
    //next(); remove this next(); 
}); 

router.post('/', function(req, res) { 
    User.findOne({ 
     tel: req.body.tel, 
    }) 
    .exec(function(err, user) { 
     var md5 = crypto.createHash('md5'), 
      password = md5.update(req.body.password) 
      .digest('hex'); 
     if (!user) { 
      return res.json({ 
       success: false, 
       message: '認證失敗,用戶名找不到' 
      }); 
     } else if (user.hash_password === password) { 
      var token = jwt.sign(user, 'whuteditor', { 
       expiresIn: "30 days" // 設置過期時間 
      }); 
      var tokenUser = new Token({ 
       token: token 
      }); 

      tokenUser.set("nickname", req.body.name); 

      tokenUser.save(function(err, token) { 
       if (err) { 
        return res.json({ 
         status: 120, 
         success: false, 
         message: "存儲出錯" 
        }); 
       } else { 
        console.log(token); 
        return res.json({ 
         status: 100, 
         success: true, 
         message: 'Enjoy your token!', 
         token: token 
        }); 
       } 

      }); 

      //res.end(); 
      //res.end(); 
     } else { 
      return res.json({ 
       status: 007, 
       success: false, 
       message: '沒有當前用戶' 
      }); 
     } 
    }); 
}); 

module.exports = router; 
+0

可以告訴我更多詳細信息嗎? –

+0

'if(!res.headersSent){res.json({...}); } else {next(); }' – danilodeveloper

+0

也許你正面臨[競爭條件](https://en.wikipedia.org/wiki/Race_condition),在響應發送給客戶端後執行回調。 – danilodeveloper

0

此錯誤時,你已經寫東西res,然後一些代碼(在鏈最有可能在下一個中間件)試圖寫入頭出現。

解決方案,您的問題可能是:刪除next()如果你寫的東西res像下面

router.get('/', function(req, res,next) { 
    res.render('login', { 
     title: '登錄界面' 
    }); 

    //Remove this next(), this causes next middleware to be executed. 
    //next(); 
}); 

更多了,這是另外一個問題,在下面的代碼

 tokenUser.save(function(err, token) { 
       if (err) { 
        return res.json({ 
         status: 120, 
         success: false, 
         message: "存儲出錯" 
        }); 
       } 
       console.log(token); 
      }); 

      return res.json({ 
       status: 100, 
       success: true, 
       message: 'Enjoy your token!', 
       token: token 
      }); 

您先發響應爲

return res.json({ 
       status: 100, 
       success: true, 
       message: 'Enjoy your token!', 
       token: token 
      }); 

and just before你正在執行tokenUser.save,它在回調中再次發送響應!這就是你錯誤的原因。

您應該重新編寫代碼,如:

tokenUser.save(function(err, token) { 
    if (err) { 
    return res.json({ 
     status: 120, 
     success: false, 
     message: "存儲出錯" 
    }); 
    } else { 
    return res.json({ 
     status: 100, 
     success: true, 
     message: 'Enjoy your token!', 
     token: token 
    }); 
    } 
    console.log(token); 
}); 

希望這有助於!

+1

我試過了,這沒有幫助 –

+0

嗯,你能告訴我請求是什麼樣子嗎?即GET /或POST/{「x」:「xx」,「y」:「xx」} –

+0

但是,這不能保存'tokenUser' –

相關問題