express框架怎么样把http请求强制转到https?
 发布于 8 年前  作者 NOOZN  6228 次预览  最后一次回复是 8 年前  来自 问答 

express框架怎么样把http请求强制转到https?

app.all('*', function (req, res, next) {
  if(req.protocol !== 'https') {
    res.redirect(301, 'https://' + req.get('host') + req.originalUrl);
  }
  return next();
})

出现error 怎么解决? rror: Can't set headers after they are sent.

6 回复
Binaryify

那是 nginx 做的事

HugoJing

怎么强制转不知道,反正这个代码不对。

app.all('*', function (req, res, next) {
  if(req.protocol !== 'https') {
    return res.redirect(301, 'https://' + req.get('host') + req.originalUrl);
  }
  return next();
})
Jealee3000

nginx +1 server { listen 80; server_name xxx.xxx.xxx; rewrite ^(.*)$ https://$server_name$1 permanent; } 这是方法之一

tomoya92

nginx做这个太简单了,为啥你要让express去做呢?

hewentaowx

你这个代码本身写的都有问题,你已经res.redirect了 相当于这段代码功能已经完成了 还return 自然报错 至于你说的怎么强转这个需要问大牛

laoqiren

监听80端口,重定向到443端口,你的代码在重定向后就应该return,即if语句里加return;

const httpServer = http.createServer((req,res)=>{ res.writeHead(301,{ ‘Location’: https://${req.headers.host}${req.url} }) res.end(); }) httpServer.listen(80); httpServer.on(‘listening’,()=>{ console.log(‘the http server has been listened at port 80’) })