Gatsby client side redirects to external URL not working on Netlify

雨燕双飞 提交于 2020-08-25 17:18:30

问题


I need to do a simple client side redirect to an external URL from a page on my Gatsby site hosted on Netlify. It works fine locally, but nothing seems to work when deployed. There also seems to be a bug with Gatsby's native createRedirect-functionality so that it doesn't allow redirecting to external URLs.

I've tried the three methods below in componentDidMount, in render as well as in callbacks from a recurring (setInterval) function call. I've also tried hijacking clicks on the links that leads to the redirect page and doing window.open(url), but nothing involving window seems to be working when deployed. Any ideas?

window.location.replace(url)
window.location.href = url
window.location = url

回答1:


You want to redirect from a url like /foo on your site to some external URL like domain.tld/bar, is that correct? If so, and you're using Netlify, then you probably want to use the Netlify _redirects file.

However, if you really want to do this inside of Gatsby, you should be able to use the componentDidMount() hook to call window.location.replace(). I've just tested on our v2 site and this works.

class About extends React.Component {
  componentDidMount() {
    window.location.replace("https://www.gatsbycentral.com/");
  }

There are some quirks during development, but this should work in production. I tested with a preview branch on Netlify and it worked for me.

If you have a specific error message you could post that as a new question.



来源:https://stackoverflow.com/questions/51636607/gatsby-client-side-redirects-to-external-url-not-working-on-netlify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!