molamola
molamola

Reputation: 269

Node.js "Cannot set headers after they are sent" error message

I read many questions on StackOverflow about this, but I couldn't find how can I solve this problem.

Here is my code.

// express 모듈을 가져와서 application 객체 생성
var express = require('express');
var app = express();

// body-parser 모듈을 가져온다.
var bodyParser = require('body-parser');
// 미들웨어의 역할을 하는 bodyParser를 통해 POST방식으로 전달된 데이터를 접근할 수 있도록
// request 객체의 body 객체를 생성한다.
app.use(bodyParser.urlencoded({extended:false}));

// 파일시스템 모듈을 가져온다.
var fs = require('fs');

// template engine 폴더 설정, 사용하는 engine은 jade
app.set('views','./views_file');
app.set('view engine','jade');

// jade로 나타내어지는 html 코드를 이쁘게 보이도록 하는 것.
app.locals.pretty = true;

// 사용자의 특정 url 입력에 대한 response로 new.jade를 rendering 시킨다.
app.get('/topic/new',function(req,res){
    res.render('new');
})

// POST 방식으로 전달된 데이터를 data 폴더에 파일로 저장
app.post('/topic', function(req,res){
    var title = req.body.title;
    var description = req.body.description;
    fs.writeFile('/data'+title,description,function(err){
        if(err){ res.status(500).send('Internal Server Error');}
        res.send('Success!');
    })
})

// 3000번 포트를 listening하고 있게 하는 것.
app.listen(3000,function(){
    console.log('Connected, 3000 port!');
})

Sorry for my korean comments.

The error message is:

Cannot set headers after they are sent.

This error occurs when I catch POST data from /topic/new.

How can I solve it?

Upvotes: 0

Views: 422

Answers (1)

riyadhalnur
riyadhalnur

Reputation: 404

The idea is to stop the execution of your function if there is any error. The return statement tells the interpreter to stop execution and return control immediately to the handler. But, also, keep in mind that if a certain part of the function is the last one being called you don't necessarily need to put return before it. So your function can be written as -

app.post('/topic', function(req,res){
  var title = req.body.title;
  var description = req.body.description;
  fs.writeFile('/data'+title,description,function(err){
    if (err) {
      return res.status(500).send('Internal Server Error');
    }

    res.send('Success!');
  });
});

Upvotes: 1

Related Questions