【问题标题】:How to call an external URL from a react express node component?如何从 React Express 节点组件调用外部 URL?
【发布时间】:2020-10-03 02:19:48
【问题描述】:

我正在尝试创建一个在另一个应用程序的标头中传递 JWT 的登录应用程序。

我从这个应用程序开始 User authentication keycloak 2 适应我的 Kecloak 安装,它工作正常。 现在我需要创建一个调用外部 URL 并传递授权令牌的组件

在这个组件中

import React, { Component } from 'react';

class callUrl1 extends Component {

  constructor(props) {
    super(props);
    this.state = { response: null };
  }

  authorizationHeader() {
    if(!this.props.keycloak) return {};
    return {
      headers: {
        "Authorization": "Bearer " + this.props.keycloak.token
      }
    };
  }

  handleClick = () => {
    console.log("callUrl1 called")
  }

}

export default callUrl1;

我需要调用外部 URL 的东西;类似:

SOME_FUNCTION('https://www.h.net/users', this.authorizationHeader())

放入handleClick。

我尝试的所有方法都会出现编译错误。

如何通过 JWT 从“http://localhost:3000”转到“https://www.h.net/users”?

【问题讨论】:

    标签: node.js reactjs jwt keycloak


    【解决方案1】:

    用于在前端 JS 中发出请求的内置库称为 Fetch。下面是一个示例,说明您可以如何在您的情况下执行此操作:

    handleClick = () => {
      fetch('https://www.h.net/users', this.authorizationHeader())
        .then((response) => {
           // do something with the response here...
        });
    }
    

    或使用异步/等待:

    handleClick = async () => {
      const response = await fetch('https://www.h.net/users', this.authorizationHeader());
      // do something with response like:
      const data = await response.json();
    }
    

    有关 Fetch 的更多信息,请查看 mdn:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    【讨论】:

    • 对不起,我不清楚。我想转到外部页面,而不是获取页面并在节点应用程序中呈现。类似于在前端应用程序中创建指向外部页面的链接,其中还包含用户单击的授权令牌。
    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2020-03-28
    • 2019-07-27
    • 1970-01-01
    • 2021-09-22
    • 2022-06-20
    • 1970-01-01
    相关资源
    最近更新 更多