Gatsby客户端重定向到外部URL,在Netlify上不起作用 [英] Gatsby client side redirects to external URL not working on Netlify
问题描述
我需要做一个简单的客户端重定向,该操作从Netlify托管的我的Gatsby网站上的页面重定向到外部URL.它在本地运行良好,但部署后似乎没有任何效果. Gatsby的本机createRedirect-功能似乎也有一个错误,因此它不允许重定向到外部URL.
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.
我在componentDidMount
,render
以及循环(setInterval
)函数调用的回调中尝试了以下三种方法.我还尝试过劫持指向重定向页面并执行window.open(url)
的链接的点击,但是在部署时,涉及到window
的所有内容似乎都不起作用.有什么想法吗?
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
推荐答案
您要从站点上的/foo
这样的URL重定向到某些domain.tld/bar
这样的外部URL,是正确的吗?如果是这样,并且您正在使用Netlify,则可能要使用 Netlify _redirects
文件.
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.
但是,如果您真的想在盖茨比内部执行此操作,则应该可以使用componentDidMount()
钩子调用window.location.replace()
.我刚刚在我们的v2网站上进行了测试,并且可以正常工作.
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/");
}
在开发过程中会有一些怪癖,但这在生产中应该起作用.我在Netlify上使用了预览分支进行了测试,并且对我有用.
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.
这篇关于Gatsby客户端重定向到外部URL,在Netlify上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!