简体   繁体   English

节点快递代理中间件句柄重定向

[英]node express proxy-middleware handle redirect

I am trying to use proxy-middleware to forward to https://npmcdn.com/ which works when I specify the final path, but when I specify shorthand urls, they are redirected to / of the local server, so return a 404.我正在尝试使用代理中间件转发到https://npmcdn.com/ ,这在我指定最终路径时有效,但是当我指定速记 url 时,它们被重定向到本地服务器的/ ,因此返回 404。

app.use('/cdn', proxy('https://npmcdn.com/'));

Then trying to hit local server...然后尝试访问本地服务器...

$.get('/cdn/lodash@4.9.0'); // works as expected
$.get('/cdn/lodash'); // is redirected to `/lodash@4.9.0` so gets 404

How can I handle redirects with my proxy server so that it is redirected to the correct remote url?如何使用代理服务器处理重定向,以便将其重定向到正确的远程 URL?

Update:更新:

@hassansin, thanks for the pointer. @hassansin,感谢您的指点。 It looks like I can fix my problem by adding a condition to handle when absolute path is given without domain, do you think it will break anything else?看起来我可以通过添加一个条件来解决我的问题,当给出没有域的绝对路径时,你认为它会破坏其他任何东西吗?

if (((statusCode > 300 && statusCode < 304) || statusCode === 201) && location) {
    // absolute path with domain
    if(location.indexOf(options.href) > -1) {
      headers.location = location.replace(options.href, slashJoin('/', slashJoin((options.route || ''), '')));
    // absolute path without domain
    } else if(location[0] === '/') {
      headers.location = options.href.replace(/\/$/,'') + headers.location;
    }
}

Update 2:更新 2:

@hassansin, how about this..? @hassansin,这个怎么样..?

    // absolute path without domain
    } else if(location[0] === '/' && req.originalUrl.slice(req.url.length*-1) === req.url) {
      headers.location = req.originalUrl.slice(0, req.url.length*-1) + headers.location;
    }

https://npmcdn.com/lodash redirects to https://npmcdn.com/lodash@4.9.0 with 302 status and location:/lodash@4.9.0 header. https://npmcdn.com/lodash使用 302 状态和location:/lodash@4.9.0标头重定向到https://npmcdn.com/lodash@4.9.0 proxy-middleware doesn't seem to handle relative 302 redirects properly. proxy-middleware似乎无法正确处理相对 302 重定向。 It only handles absolute redirects . 它只处理绝对重定向

This will include the baseUrl back on the redirect location这将包括 baseUrl 回到重定向位置

  • /cdn/lodash will redirect to /lodash@4.9.0 /cdn/lodash将重定向到/lodash@4.9.0
    • userResHeaderDecorator will rewrite it to /cnd/lodash@4.9.0 userResHeaderDecorator会将其重写为/cnd/lodash@4.9.0
  • request to /cdn/lodash@4.9.0 will work properly/cdn/lodash@4.9.0的请求将正常工作
app.use(
  '/$BASEURL',
  proxy(`http://somewhere-else.com`, {
    userResHeaderDecorator(headers, userReq, userRes) {
      if (userRes.statusCode.toString().startsWith('30') 
        && !headers.location.includes('://'))
        headers.location = userReq.baseUrl + headers.location
      return headers
    },
  })
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM