我的网页上有一个指向“/auth/facebook”的链接
<a href='/auth/facebook'>Log In with Facebook</a>
这很好用。
我需要在 React 组件的 Js 中做同样的事情。这是代码
<a className='btn btn-primary btn-outline'
role='button'
onClick={() => $.get('/auth/facebook')}>
Sign up/in to buy
</a>
当触发 Onclick 时,控制台会输出错误,就好像我正在尝试执行跨站点请求一样。
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…Fauth%2Ffacebook%2Fcallback&scope=public_profile&client_id=XXXX. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
我的理解是链接和 $.get 调用都应该转到我的服务器“localhost”并触发相同的路由。 这两个调用有什么区别?
最佳答案
$.GET
只是要从服务器加载数据(假设它有效,并且没有抛出 CORS 错误)。它不处理重定向。如果由于某种原因你不能使用 href
属性,你可以这样做:
onClick={() => window.location.href = '/auth/facebook'}
因为看起来您正在使用 React,您可能还会受益于使用像 react-router ( https://github.com/ReactTraining/react-router ) 这样的路由器模块,它公开了一个 <Link>
组件以使您的 UI 与 URL 保持同步。
关于javascript - href 和 $.get 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40595713/