簡體   English   中英

錯誤:發送到客戶端后無法設置標頭

[英]Error : Cannot set headers after they are sent to the client

當我點擊注冊路線時,“req.body”沒有選擇任何 POST 值,但是每當在 Postman 上測試相同的代碼時 - 使用 body raw 方法 - 值顯示。

const router = require('express').Router();
const bodyParser = require('body-parser');
const Promise = require('bluebird');

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({
  extended: true
}));


const registration = require('./services/registration');

router.get('/', (req, res, next) => {
  res.send('Admin Welcome');
});

router.get('/signup', (req, res, next) => {
  res.render('user/signup');
});

router.post('/signup', (req, res, next) => {
  res.send(req.body);
  registration.registration(req.body);
  .then(ok=>{
    res.redirect('signin')
  })
  .catch(err => {
    res.render('error', {message: err})
  })
})

router.get('/signin', (req, res, next) => {
  res.render('user/signin');
});

原始代碼

router.post("/signup", (req, res, next) => {
  res.send(req.body);
  registration
    .registration(req.body)
    .then(ok => {
      res.redirect("signin");
    })
    .catch(err => {
      res.render("error", { message: err });
    });
});

res對象表示 Express 應用在收到 HTTP 請求時發送的 HTTP 響應。 在以下鏈接中,您可以看到為res對象公開的所有方法: https : //expressjs.com/en/api.html#res

您在路由處理程序開始時使用的方法是:

res.send([正文])

並且可以從文檔中讀取它發送 HTTP 響應。 現在您只能發送該響應一次,否則您將收到錯誤消息:

Error : Cannot set headers after they are sent to the client

您在處理程序中嘗試做的是將結果重定向到“登錄”頁面,之后已經使用res.send(req.body)發送響應。

以這條假路由為例:

router.post("/example", (req, res, next) => {
  res.send('1');
  res.send('2');
  res.send('3');
});

與您可能相信的相反,它不會返回值 (1,2,3),而是實際返回值 1 並引發前面描述的錯誤。

最后要解決您的問題,您需要刪除包含res.send(req.body)並仔細檢查registration.registration服務是否正確處理提供的數據,在這種情況下為req.body

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM