Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 节点js-如何获取url名称?_Node.js_Express - Fatal编程技术网

Node.js 节点js-如何获取url名称?

Node.js 节点js-如何获取url名称?,node.js,express,Node.js,Express,我试图从www重定向到非www,但做不到。 看看我的代码: function wwwRedirect(req, res, next) { console.log('Got url ' + req.headers.host) // return example.com (without 'www'), even if I go to www.example.com console.log('req.get("host") ' + req.get('host')) // same if

我试图从www重定向到非www,但做不到。 看看我的代码:

function wwwRedirect(req, res, next) {
  console.log('Got url ' + req.headers.host)  // return example.com (without 'www'), even if I go to www.example.com
  console.log('req.get("host") ' + req.get('host')) // same
  if (req.headers.host.slice(0, 4) === 'www.') { // not working, cause req.headers.host doesn't contain 'www', even if Im connecting to www.example.com
      var newHost = req.headers.host.slice(4);
      return res.redirect(301, req.protocol + '://' + newHost + req.originalUrl);
      console.log('New url ' + req.protocol + '://' + newHost + req.originalUrl)
  }
  next();
};

app.set('trust proxy', true);
app.use(wwwRedirect);
请看上面所有的评论。
所以,我不能重定向。我做错了什么?为什么req.headers.host不包含“www.”即使我连接了“www.example.com”

您也可以这样做:

app.use(函数(请求、恢复、下一步){
if(req.headers.host.match(/^www/)!==null){
res.redirect('http://'+req.headers.host.replace(/^www\./,'')+req.url);
}否则{
next();
}

})
这意味着您实际上没有连接到
www.example.com
@SLaks我确实连接到了www.example.com,我从不同的浏览器尝试了在Fiddler或浏览器开发工具中看到了哪些标题?@SLaks您可以在chrome开发工具的屏幕截图上看到标题:请再阅读一次问题,特别是console.log附近代码中的注释