问题
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