【问题标题】:How to add header params to Iframe in ReactJS如何在 ReactJS 中向 Iframe 添加标头参数
【发布时间】:2021-07-16 04:32:17
【问题描述】:

我正在尝试在我的 React 应用程序中添加一个 iframe 组件。但我需要向 url 添加一个身份验证密钥。

我是 React 新手,我正在尝试这种方式:

import React, {useEffect, useState} from 'react';

function IframeComp() {
  const [content, setContent] = useState('');


  useEffect(() => {
    // Fetch the content using the method of your choice
    const fetchedContent = '<h1>Some HTML</h1>';
    setContent(fetchedContent);
  }, []);


  return (
      <iframe sandbox id="inlineFrameExample"
              title="Inline Frame Example"
              width="300"
              height="200"
              src={content}>
      </iframe>
  );
}

export default IframeComp;

我在 Stack Overflow (Is it possible to add Request Headers to an iframe src request?) (https://github.com/courajs/pdf-poc/blob/master/script.js) 中找到了解决方案,但它不在 React 中。

我认为我必须这样做:

var xhr = new XMLHttpRequest();

  xhr.open('GET', url);
  xhr.onreadystatechange = handler;
  xhr.responseType = 'blob';
  headers.forEach(function(header) {
    xhr.setRequestHeader('Authorization', 'JWT eyJ0eXAiOiJK');
  });
  xhr.send();

我走对了吗?

【问题讨论】:

    标签: javascript reactjs iframe


    【解决方案1】:

    不,不能将标头参数添加到 iframe src-tag。

    但作为一种替代方法,与您的方式类似,您可以使用 fetch-API 或 axios 使用所需的 Http-Headers 获取 html,并将 html 插入到您的 src-tag 中。

    例子:

    import React, { useEffect, useState } from "react";
    
    function IframeComp() {
      const [content, setContent] = useState('');
    
      useEffect(() => {
        fetch("https://www.example.com", {
          headers: {"Authorization", "JWT eyJ0eXAiOiJK"}
        })
          .then(response => response.text())
          .then(data => setContent(data))
          .catch(err => err)
      }, []);
    
      return (
          <iframe sandbox id="inlineFrameExample"
                  title="Inline Frame Example"
                  width="300"
                  height="200"
                  src={content}>
          </iframe>
      );
    }
    
    export default IframeComp;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      相关资源
      最近更新 更多