오류: 클라이언트에 보낸 후 헤더를 설정할 수 없습니다.
Node.js는 처음이라 문제가 좀 있습니다.
Node.js 4.10 및 Express 2.4.3을 사용하고 있습니다.
http://127.0.1:8888/auth/facebook에 접속하려고 하면 http://127.0.1:8888/auth/facebook_callback으로 리다이렉트 됩니다.
그 후, 다음의 에러가 발생했습니다.
Error: Can't render headers after they are sent to the client.
at ServerResponse.<anonymous> (http.js:573:11)
at ServerResponse._renderHeaders (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:64:25)
at ServerResponse.writeHead (http.js:813:20)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:28:15
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:113:13
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/strategyExecutor.js:45:39)
at [object Object].pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:32:3)
at [object Object].halt (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:29:8)
at [object Object].redirect (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/authExecutionScope.js:16:8)
at [object Object].<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/auth.strategies/facebook.js:77:15)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:195:11)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at param (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:189:13)
at pass (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:191:10)
at Object.router [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/router.js:197:6)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at Object.auth [as handle] (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect-auth/lib/index.js:153:7)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:150:23)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at HTTPServer.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:211:3)
at Object.handle (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:105:14)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:198:15)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/patch.js:50:20)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:162:13)
at next (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/http.js:207:9)
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:323:9
at /home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session.js:338:9
at Array.<anonymous> (/home/eugene/public_html/all_things_node/projects/fb2/node_modules/connect/lib/middleware/session/memory.js:57:7)
at EventEmitter._tickCallback (node.js:126:26)
다음은 내 코드입니다.
var fbId= "XXX";
var fbSecret= "XXXXXX";
var fbCallbackAddress= "http://127.0.0.1:8888/auth/facebook_callback"
var cookieSecret = "node"; // enter a random hash for security
var express= require('express');
var auth = require('connect-auth')
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: cookieSecret}));
app.use(auth([
auth.Facebook({
appId : fbId,
appSecret: fbSecret,
callback: fbCallbackAddress,
scope: 'offline_access,email,user_about_me,user_activities,manage_pages,publish_stream',
failedUri: '/noauth'
})
]));
app.use(app.router);
});
app.get('/auth/facebook', function(req, res) {
req.authenticate("facebook", function(error, authenticated) {
if (authenticated) {
res.redirect("/great");
console.log("ok cool.");
console.log(res['req']['session']);
}
});
});
app.get('/noauth', function(req, res) {
console.log('Authentication Failed');
res.send('Authentication Failed');
});
app.get('/great', function( req, res) {
res.send('Supercoolstuff');
});
app.listen(8888);
제 코드에 무슨 문제가 있는지 알 수 있을까요?
resExpress의 오브젝트는 Node.js의 서브클래스입니다(http.js 소스를 읽습니다).전화할 수 있습니다.res.setHeader(name, value)이 전화할 만큼 res.writeHead(statusCode) .끝나고writeHead할 수 은 「」 「」 「」 「」 「」 뿐입니다.res.write(data)으로 「」res.end(data).
에러:보낸 후 헤더를 설정할 수 없습니다."는 사용자가 이미 본문 또는 완료 상태이지만 일부 함수가 헤더 또는 상태 코드를 설정하려고 시도했음을 의미합니다.이 에러가 발생했을 경우는, 본문의 일부가 이미 기입된 후에 헤더를 송신하려고 하는 것을 찾아 주세요.예를 들어 실수로 두 번 호출된 콜백이나 본문이 전송된 후 발생한 오류를 찾습니다.
같은 경우에는 요, 전화했잖아요.res.redirect()끝나다에러)를 발생시켰습니다.res.reqnull는, 의 「」에, 「」는 「」로 되어 있습니다function(req, res, next)(콜백 내가 아님) Connect가 콜백을 검출하여 500 에러 페이지를 송신하려고 했습니다., 되어 있기 Node.의 Node.js는 Node.jssetHeader당신이 본 오류를 던졌습니다.
Node.js/Express 응답 메서드 및 호출해야 하는 타이밍의 포괄적인 목록:
응답은 선두에 있어야 하며 선두에 남아 있어야 합니다.
res.writeContinue()res.statusCode = 404res.setHeader(name, value)res.getHeader(name)res.removeHeader(name)res.header(key[, val])(익스프레스만)res.charset = 'utf-8'express 메서드에만 을 줍니다 (Express ", Express "의 영향을 받습니다.)res.contentType(type)(익스프레스만)
응답은 머리에 있어야 하며 본문이 됩니다.
응답은 머리/몸통 중 하나에 있을 수 있으며 본문에 남습니다.
응답은 Head/Body에 있을 수 있으며 Finished가 됩니다.
응답은 Head/Body 중 하나일 수 있으며 현재 상태를 유지합니다.
응답은 Head에 있어야 하며 Finished가 됩니다.
return next([err])익스))) ()- 내의
function(req, res, next)익스))) () res.send(body|status[, headers|status[, status]])(익스프레스만)res.attachment(filename)(익스프레스만)res.sendfile(path[, options[, callback]])(익스프레스만)res.json(obj[, headers|status[, status]])(익스프레스만)res.redirect(url[, status])(익스프레스만)res.cookie(name, val[, options])(익스프레스만)res.clearCookie(name[, options])(익스프레스만)res.render(view[, options[, fn]])(익스프레스만)res.partial(view[, options])(익스프레스만)
이 Q&A의 답변 중 일부는 틀렸습니다.받아들여진 답변도 실용적이지 않기 때문에 알기 쉬운 답변을 투고하고 싶습니다.제 답변에는 반복적으로 게시된 오류의 99%가 포함됩니다.에러의 실제의 이유에 대해서는, 인정된 답변을 참조해 주세요.
HTTP는 요청당 1개의 응답이 필요한 사이클을 사용합니다.클라이언트가 요구(POST 또는 GET 등)를 송신하면, 서버는 1개의 응답만 송신합니다.
다음 오류 메시지:
오류: 헤더를 보낸 후에는 헤더를 설정할 수 없습니다.
보통 1개의 요청에 대해 여러 개의 응답을 보낼 때 발생합니다.다음 함수가 요청당1회만 호출되는지 확인합니다.
res.json()res.send()res.redirect()res.render()
(그리고 거의 사용되지 않는 몇 가지 답변도 확인)
이러한 res 함수가 호출되면 루트 콜백은 반환되지 않습니다.함수 끝 또는 반환문에 도달할 때까지 계속 실행됩니다.때 때는 할 수 .return res.send().
다음 코드를 예로 들 수 있습니다.
app.post('/api/route1', function(req, res) {
console.log('this ran');
res.status(200).json({ message: 'ok' });
console.log('this ran too');
res.status(200).json({ message: 'ok' });
}
POST 요구가 /api/route1로 전송되면 콜백 내의 모든 회선이 실행됩니다.A Cannot set headers after that sended 오류 메시지가 표시되는 이유는 다음과 같습니다.res.json()는 2회 호출됩니다.즉, 2개의 응답이 송신됩니다.
요청당 하나의 응답만 보낼 수 있습니다!
위의 코드 샘플의 오류는 명백했습니다.보다 일반적인 문제는 브런치가 여러 개 있는 경우입니다.
app.get('/api/company/:companyId', function(req, res) {
const { companyId } = req.params;
Company.findById(companyId).exec((err, company) => {
if (err) {
res.status(500).json(err);
} else if (!company) {
res.status(404).json(); // This runs.
}
res.status(200).json(company); // This runs as well.
});
}
콜백이 연결된 이 루트는 데이터베이스 내의 회사를 찾습니다.않는 는, 「회사 안」으로.else if404번그 후, 회답도 보내는 다음 스테이트먼트로 넘어갑니다.이제 두 개의 응답을 보냈고 오류 메시지가 나타납니다.하려면 , 반드시 만을 송신합니다.
.exec((err, company) => {
if (err) {
res.status(500).json(err);
} else if (!company) {
res.status(404).json(); // Only this runs.
} else {
res.status(200).json(company);
}
});
또는 응답 전송 시 반환:
.exec((err, company) => {
if (err) {
return res.status(500).json(err);
} else if (!company) {
return res.status(404).json(); // Only this runs.
}
return res.status(200).json(company);
});
큰 죄인은 비동기 함수입니다.이 질문의 함수를 예로 들어 보겠습니다.
article.save(function(err, doc1) {
if (err) {
res.send(err);
} else {
User.findOneAndUpdate({ _id: req.user._id }, { $push: { article: doc._id } })
.exec(function(err, doc2) {
if (err) res.send(err);
else res.json(doc2); // Will be called second.
})
res.json(doc1); // Will be called first.
}
});
비동기함수)가 있습니다.findOneAndUpdate()을 참조해 주세요를 참조해 주세요.( 「」 「」 「」).errfindOneAndUpdate() 에 비동기적이기 때문에res.json(doc1)즉시 호출됩니다..findOneAndUpdate() . 。res.json(doc2) else그러면 호출됩니다.이제 두 개의 응답이 전송되었으며 "헤더를 설정할 수 없습니다" 오류 메시지가 나타납니다.
이음음음음음음음음 뺄 수 있다.res.json(doc1)하려면 , 「」를 참조해 주세요res.json()으로는 '하다, 하다, 하다, 하다'라고 쓸 수 있어요.res.json({ article: doc1, user: doc2 }).
나도 한동안 이 오류가 있었어.(희망) 머리를 싸매서 여기에 참고용으로 쓰고 싶었던 것 같아요.
접속 또는 표현에 미들웨어를 추가하는 경우(접속 상에 구축되어 있음)에는app.use, ,, to, to, 이, 이, 가, 가, 가, to, to, to, to, to, to, to,Server.prototype.stackconnect ((최소한 현재)와 함께)npm install connect하면, 해, 「Github」, 「Github」, 「Gitub」를 호출합니다.」를 호출합니다.(request, response, next)★★★★★★ 。
문제는 미들웨어 항목 중 하나가 응답 본문 또는 헤더에 쓰이지만(어떤 이유로든) 호출하지 않고 핵심으로 호출하는 경우입니다.Server.prototype.handle메서드가 완료되면 다음 사항을 알 수 있습니다.
- 스택에 더 이상 항목이 없습니다.
- 그그
response.headerSent정말이에요.
그래서 오류가 발생합니다., 이 는 (으로부터의) 응답일 입니다.http.js스스: :
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Cannot ' + req.method + ' ' + req.url);
저기, '아까', '아까', '아까', '아까', '아까', '아까', '아까'를 부르고 있어요.res.setHeader('Content-Type', 'text/plain'); 그 에 있을 rendermethod, 호출 응답 없음.end는 다음과 같습니다.
response.setHeader("Content-Type", "text/html");
response.write("<p>Hello World</p>");
모든 것을 구조화해야 하는 방법은 다음과 같습니다.
뛰어난 미들웨어
// middleware that does not modify the response body
var doesNotModifyBody = function(request, response, next) {
request.params = {
a: "b"
};
// calls next because it hasn't modified the header
next();
};
// middleware that modify the response body
var doesModifyBody = function(request, response, next) {
response.setHeader("Content-Type", "text/html");
response.write("<p>Hello World</p>");
response.end();
// doesn't call next()
};
app.use(doesNotModifyBody);
app.use(doesModifyBody);
문제가 있는 미들웨어
var problemMiddleware = function(request, response, next) {
response.setHeader("Content-Type", "text/html");
response.write("<p>Hello World</p>");
next();
};
가 있는 하는데, 응답 헤더를 호출하지 .response.end()를 호출합니다.next()(미국의)
, 그 때문이라는 것을 깨달았습니다.res.redirectreturn즉 "Discriptions", "Discriptions", "Discriptions"의next직후에도 되었습니다: function직직직 function function function function function function function function function function function function function function function function function function function function 。
auth.annonymousOnly = function(req, res, next) {
if (req.user) res.redirect('/');
next();
};
다음 중 어느 것이어야 합니까?
auth.annonymousOnly = function(req, res, next) {
if (req.user) return res.redirect('/');
next();
};
많은 사람들이 이 오류를 경험합니다.이것은 비동기 처리와 혼동됩니다.코드 중 일부는 첫 번째 틱에서 헤더를 설정하고 다음 틱에서 비동기 콜백을 실행하고 있을 가능성이 높습니다.그 사이에 응답 헤더가 송신됩니다만, 그 후(30X 리다이렉트등) 이후의 헤더가 추가의 헤더를 추가하려고 합니다만, 응답 헤더가 이미 송신되었기 때문에, 너무 늦습니다.
오류의 원인이 무엇인지 정확히 알 수 없지만, 조사해야 할 잠재적인 영역으로 콜백을 살펴보십시오.
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★app.configure() 하면 돼app.use최고 수준의 범위로 직접 이동할 수 있습니다.
Facebook 및 기타 서드파티 인증 프로바이더를 실행하는 everyauth 모듈도 참조하십시오.
에러는 RND 후에 자동적으로 검출됩니다.
1) 에러 코드:
return res.sendStatus(200).json({ data: result });
2) 성공 코드
return res.status(200).json({ data: result });
차이점은 status() 대신 sendStatus()를 사용했다는 것입니다.
나는 이 문제에 대해 곰곰이 생각해 보았지만, 그것은 콜백 처리에 부주의한 실수 때문에 일어났다.반환되지 않은 콜백으로 인해 응답이 두 번 설정됩니다.
제 프로그램에는 요청을 검증하고 DB를 조회하는 코드가 있었습니다.오류 여부를 검증한 후 index.js를 검증 오류와 함께 호출하고 있었습니다.검증에 성공하면 DB에 성공/실패가 발생합니다.
var error = validateRequestDetails("create",queryReq);
if (error)
callback(error, null);
else
some code
callback(null, success);
콜백이 호출되어 응답이 설정되는 경우 검증에 실패합니다.하지만 돌아오지 않았다.따라서 이 메서드는 계속 db로 이동하여 success/failure를 누릅니다.같은 콜백을 다시 콜하여 응답을 2회 설정합니다.
따라서 해결 방법은 간단합니다.콜백을 '반환'하여 오류가 발생하면 메서드가 계속 실행되지 않도록 하고 응답 개체를 한 번 설정해야 합니다.
var error = validateRequestDetails("create",queryReq);
if (error)
callback(error, null);
return;
else
some code
callback(null, success);
이러한 유형의 오류는 응답을 보낸 후 문을 통과하면 발생합니다.
예를 들어 다음과 같습니다.
res.send("something response");
console.log("jhgfjhgsdhgfsdf");
console.log("sdgsdfhdgfdhgsdf");
res.send("sopmething response");
되면, 의 에러가 됩니다.응답이 송신되면, 다음과 같이 됩니다.res.send을 사용하다
원하는 작업이 있으면 응답을 보내기 전에 수행해야 합니다.
이 에러는, 2 회신을 송신했을 때에 발생합니다.예를 들어 다음과 같습니다.
if(condition A)
{
res.render('Profile', {client:client_});
}
if (condition B){
res.render('Profile', {client:client_});
}
}
이고, 두 A가 참이라고 합니다.render날 예요.
res.end 또는 res.send 뒤에 next() 함수를 호출하려고 할 때 이 오류가 발생할 수 있습니다.함수에 res.send 또는 res.end 뒤에 next()가 있는 경우 삭제를 시도합니다.주의: 여기서 next()는 클라이언트에 대한 응답(res.send 또는 res.end) 후 다시 응답하기 위해 몇 가지 코드를 실행하려고 시도하고 있다는 것을 의미하며, 이는 합법적이지 않습니다.
예:
router.get('/',function (req,res,next){
res.send("request received");
next(); // this will give you the above exception
});
next()위 기능에서 작동하게 됩니다.
돼요.return " " "와 같은 키워드:return res.redirect("/great");리고고 그과효효 !었!!!!
를 사용하고 있는 는, 「」를 합니다.return그 err블록. 이것은 이 오류가 발생할 수 있는 시나리오 중 하나입니다.
userModel.createUser(data, function(err, data) {
if(err) {
res.status = 422
res.json(err)
return // without this return the error can happen.
}
return res.json(data)
})
version " " 。v10.16.0.4.16.4
이 에러의 원인은, res.send, res.json 등 앞에 return 키워드를 추가하지 않은 경우입니다.
제 경우, 문제의 원인은 304 응답(캐시)입니다.
가장 쉬운 솔루션:
app.disable('etag');
더 많은 제어를 원하는 경우 다음 대체 솔루션:
여기에 도달했지만 다른 어떤 해결책도 도움이 되지 않은 경우에는 이미지 업로드를 처리했지만 타임아웃을 처리하지 않은 루트에 나타나 있습니다.따라서 업로드가 너무 오래 걸리고 타임아웃이 된 경우 타임아웃 응답이 전송된 후 콜백이 실행되었을 때 res.send()를 호출하여 헤더가 전송되었을 때 크래시가 발생하였습니다.타임아웃을 설명하도록 이미 설정되어 있습니다.
이것은 매우 짧은 타임아웃을 설정하고 꽤 큰 이미지로 루트를 타격함으로써 쉽게 재현할 수 있었고, 그때마다 크래시가 재현되었다.
이하였습니다.이것은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★그때, 저는 채널 등록을 취소하지 않았습니다.componentWillUnmount반응해 주세요.
가 여러 개의 코드를 하십시오.res.send()1회'그' 입니다 ('아예'''아예'...
restify 노드 어플리케이션에서 이 문제가 발생하였습니다.실수는 이었습니다.
switch (status) {
case -1:
res.send(400);
case 0:
res.send(200);
default:
res.send(500);
}
저는 브레이크 없이 스위치를 사용하여 여러 가지 사례를 처리하고 있었습니다.스위치 케이스에 대해 잘 모르시는 분들은 중단 없이 키워드 return을 입력해 주세요.대소문자의 코드와 그 다음 행은 반드시 실행됩니다. 싱글을 res.send 개의 res.send라고 가 붙은
오류: 클라이언트에 보낸 후 헤더를 설정할 수 없습니다.
했습니다.res.send()return res.send(200)
switch (status) {
case -1:
res.send(400);
break;
case 0:
res.send(200);
break;
default:
res.send(500);
break;
}
그냥 이걸 기울였어요.이 기능을 통해 응답을 전달할 수 있습니다.
app.use(function(req,res,next){
var _send = res.send;
var sent = false;
res.send = function(data){
if(sent) return;
_send.bind(res)(data);
sent = true;
};
next();
});
이 문제는 응답이 클라이언트에 전달되고 다시 응답을 하려고 할 때 발생합니다.이 에러의 원인이 되고 있는 클라이언트에 대한 응답을 다시 반환하고 있는 것을 코드를 체크할 필요가 있습니다.회신을 원하실 때 한 번 확인 후 회신해 주십시오.
res.send("your result") 전에 앱.get에서 상태를 설정하지 않도록 검색하십시오.
방금 삭제했습니다.
res.sendStatus(200);
그 후에 반응합니다!!!
res.send("your result");
새로운 버전의 노드에서는 부울식이 지원됩니다.응답을 이미 전송했는지 여부를 확인하는 데 사용할 수 있습니다.
if (!res.headersSent) // if doesn't sent yet
res.status(200).send({ "message": "This is a message" })
참고! 이 방법은 문제 해결에 도움이 되지만 올바른 해결 방법이 아니므로 권장하지 않습니다.
응답을 두 번 이상 보내는 것은 수정해야 하는 코드에 문제가 있음을 나타냅니다(함수에서 두 개의 리턴 문을 연속으로 사용하는 것과 같습니다).버그입니다).
이 middlware를 추가하면 동작합니다.
app.use(function(req,res,next){
var _send = res.send;
var sent = false;
res.send = function(data){
if(sent) return;
_send.bind(res)(data);
sent = true;
};
next();
});
위에서 도움을 받지 못하는 경우: for noobs 이 오류의 이면에 있는 이유는 요청을 여러 번 전송하기 때문입니다.- 1 . ' : 。
module.exports = (req,res,next)=>{
try{
const decoded = jwt.verify(req.body.token,"secret");
req.userData = decoded;
next();
}catch(error){
return res.status(401).json({message:'Auth failed'});
}
next();
}
위의 호출에서 next()를 두 번 누르면 오류가 발생합니다.
router.delete('/:orderId', (req, res, next) => { Order.remove({_id:req.params.orderId},(err,data)=>{ if(err){ **res.status(500).json(err);** }else{ res.status(200).json(data); } *res.status(200).json(data);* }) })
여기 응답은 이미 응답을 보냈는지 두 번 확인합니다.
이것은 노드에 가까울 가능성이 매우 높으며, 99%는 이중 콜백으로 응답하거나 next()를 두 번 응답하는 경우가 많습니다.루프 내에서 next()를 사용하는 것이 문제가 해결되었습니다.루프에서 next()를 삭제하거나 여러 번 호출을 중지합니다.
가지 중 하나를 res.end() 콜의 합니다.
예를들면
app.post("/auth", function (request, res) {
var username = request.body.username;
var password = request.body.password;
if (username && password) {
let sql =
"SELECT username, worker_name, worker_surname, id FROM workers where username = ? AND password=?";
con.query(sql, [username, password], function (error, results, fields) {
if (results.length > 0) {
res.status(200).send(results);
res.end();
}
res.status(404).send("Incorrect Username and/or Password!");
});
} else {
res.send("Please enter Username and Password!");
}
res.end();
});
이 문제는 다음부터 발생하였습니다./auth/facebook에는, 블록에 하지 말아 주세요.또, JavaScript의 것과 .클라이언트로부터 이미 응답을 송신한 후에는, 다음의 후계 블록에 대해서 다른 함수를 설정하지 말아 주세요.또, 자바 스크립트의 동기화에 관계하고 있습니다.
깊이 이해하기 위해 이 코드와 같습니다.
async function getRequest(){
let data = await API.get();
return data;
let json = data.json(); // will not read this line
}
의 경우, ★★★★★★★★★★★★★★★★★★★★.console.log("ok cool."); ★★★★★★★★★★★★★★★★★」console.log(res['req']['session'])에 놓아야 한다res.redirect("/great")
이치에 맞기를 바랍니다.어서오세요:)
루프 함수 내에서 응답을 보내려고 했을 때 비슷한 오류가 발생하였습니다.간단한 해결방법은 이 시스템을
res.send "send response" ;
응답 헤더를 1회밖에 송신할 수 없기 때문에, 루프로부터 해방됩니다.
https://www.tutorialspoint.com/nodejs/nodejs_response_object.htm
코드를 확인합니다.저는 같은 if 스테이트먼트에서 res.status를 두 번 사용했습니다.첫 번째는 헤더 상태를 설정하고 두 번째는 헤더 상태를 변경하려고 시도하여 문제가 발생하였습니다.
Typescript에서 문제는 메시지를 받은 후 웹 소켓 연결을 닫지 않았다는 것입니다.
WebSocket.on("message", (data) => {
receivedMessage = true;
doSomething(data);
localSocket.close(); //This close the connection, allowing
});
내가 약속을 어길 때 이 문제가 있었다.약속 내부의 약속은 서버에 200을 반환하지만, 그 후 외부 약속의 catch 스테이트먼트는 500을 반환합니다.이걸 고치고 나니 문제가 사라졌어요.
언급URL : https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client
'programing' 카테고리의 다른 글
| Big Decimal을 정수로 변환 (0) | 2022.12.26 |
|---|---|
| Python에서 멀티프로세싱을 사용하는 동안 어떻게 기록해야 합니까? (0) | 2022.12.26 |
| KEY 키워드의 의미는 무엇입니까? (0) | 2022.12.26 |
| PHP 파일이 일반 텍스트로 표시되는 이유는 무엇입니까? (0) | 2022.12.07 |
| MySQL 검색 및 필드의 일부 텍스트 바꾸기 (0) | 2022.12.07 |
