簡體   English   中英

如何從 URL 中刪除訪問令牌

[英]How to remove accesstoken from the URL

現在我正在從 url 獲取訪問令牌。 我在后端使用 GET 請求,它將 accesstoken 傳遞給 URL。 他們的關鍵問題是,在我成功登錄后,訪問令牌保留在 URL 中。 我不知道如何擺脫它。

function App() {
  // ( getSpotifyTokenFromUrl() ) That function is getting me the token from the url
  const params = getSpotifyTokenFromUrl();
  const token = params.access_token;

  return (
    <Router>
      <div className="app">
        {token ? 
          <Route path="hompage">
            <Homepage spotify={spotify}/>
          </Route>
        : <Home />}
      </div>
    </Router>
  )

我也嘗試在index.js文件中這樣做

ReactDOM.render(
  <Router>
    <App>
      <Route exact path="/hompage" component={Homepage} />
    </App>
  </Router>,
  document.getElementById('root'));

這是我的后端代碼的一小部分,它將令牌傳遞給瀏覽器。 也許我必須再次重定向,但是如何呢?

res.redirect('http://localhost:3000/#' +
  querystring.stringify({
    access_token: access_token,
    refresh_token: refresh_token
  }));

我知道為時已晚,但也許答案會幫助其他人。 我在這個鏈接中找到了您的答案: https ://gist.github.com/DavidWells/ea3e43886534ff7c3efb6d389766e588 您可以像這樣更改 App 功能:

function App() {
   const {location, history} = window;
   const {search} = location;
   const params = getSpotifyTokenFromUrl();
   var token = null;
   if (params !== null) {
     token = params.access_token;
     if (search && search.indexOf('access_token') !== -1 && history && 
         history.replaceState) {
         // remove access_token from url
         const cleanSearch = search.replace(/(\&|\?)access_token[^\&]*/g, 
         '').replace(/^&/, '?');
         // replace search params with clean params
         const cleanURL = location.toString().replace(search, cleanSearch)
         // use browser history API to clean the params
         history.replaceState({}, '', cleanURL)
         }
       }
   return (
     <Router>
      <div className="app">
       {token ? 
        <Route path="hompage">
          <Homepage spotify={spotify}/>
        </Route>
        : <Home />}
     </div>
    </Router>
    )     
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM