【问题标题】:Parse error when fetching html via Firebase to React通过 Firebase 获取 html 到 React 时解析错误
【发布时间】:2019-12-28 19:50:54
【问题描述】:

我正在尝试使用 Firebase 创建一个云函数端点,我可以从中获取 html 作为字符串。 “惊人”的想法是在带有 fetch 的 React 组件中显示 HTML 页面。这是 Firebase express 的实现:

const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();

app.get('/page3', (request, response) => {
  cors(request, response, () => {
    response.send(
          '<div><p>Det är en sida</p><section><h1>Return of the King</h1><h2><span>A Long-Expected Party</span></h2><p><br></br></p><p>When Mr. Bilbo Baggins of Bag End announced</p><p>Bilbo was very rich and for fame, wealth.</p><p>‘It will have to be paid for,’ they said. ‘It isn’t natural, and trouble will come of it!’</p><p><br></br></p><p><br></br></p><p><span style="background-color: rgb(255, 255, 0);">Note: Look at this link to understand more</span>: <a href="www.svt.se" target="_blank">svt.se</a></p><p><br></br></p><p><br></br></p><p>‘A very nice well-spoken gentlehobbit is Mr. Bilbo, as I’ve always said,’ the Gaffer declared. With perfect truth: for Bilbo was very polite to him.</p><p>‘But what about this Frodo that lives with him?’ asked Old Noakes of Bywater. ‘Baggins is his name, but he’s more than half a Brandybuck, they say.’</p><p><br></br></p><p>‘And and right agin the Old Forest.’</p><p>‘Very much like Mr. Bilbo, Baggins; there was never much to tell of him, till he was drownded.’</p><p><br></br></p></section></div>'
      )
    });  
})

exports.app = functions.https.onRequest(app);

在 React 应用程序中,我只想获取并解析端点提供的 html 字符串,然后尝试记录它。我得到的错误是:

<parseerror style= "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
    <h3> This page contains the following errors: </h3>
    <div style="font-family:monospace;font-size:12px"> error on line 1 at column 1:     Extra content at the end of the document
    </div>

然后在 Chrome 中出现黄色警告:

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://easye-9364e.firebaseapp... with MIME type text/html. See https://www.chromestatus.com/feature/56 for more details.

这里有什么问题?

【问题讨论】:

    标签: javascript reactjs firebase cors google-cloud-functions


    【解决方案1】:

    你错过了这条线:

    app.use(cors);

    app.get()之前

    所以你的代码应该是这样的:

    const functions = require('firebase-functions');
    const express = require('express');
    const cors = require('cors')({origin: true});
    const app = express();
    
    app.use(cors);
    app.get('/page3', (request, response) => {
      cors(request, response, () => {
        response.send(
              '<div><p>Det är en sida</p><section><h1>Return of the King</h1><h2><span>A Long-Expected Party</span></h2><p><br></br></p><p>When Mr. Bilbo Baggins of Bag End announced</p><p>Bilbo was very rich and for fame, wealth.</p><p>‘It will have to be paid for,’ they said. ‘It isn’t natural, and trouble will come of it!’</p><p><br></br></p><p><br></br></p><p><span style="background-color: rgb(255, 255, 0);">Note: Look at this link to understand more</span>: <a href="www.svt.se" target="_blank">svt.se</a></p><p><br></br></p><p><br></br></p><p>‘A very nice well-spoken gentlehobbit is Mr. Bilbo, as I’ve always said,’ the Gaffer declared. With perfect truth: for Bilbo was very polite to him.</p><p>‘But what about this Frodo that lives with him?’ asked Old Noakes of Bywater. ‘Baggins is his name, but he’s more than half a Brandybuck, they say.’</p><p><br></br></p><p>‘And and right agin the Old Forest.’</p><p>‘Very much like Mr. Bilbo, Baggins; there was never much to tell of him, till he was drownded.’</p><p><br></br></p></section></div>'
          )
        });  
    })
    
    exports.app = functions.https.onRequest(app);
    

    【讨论】:

    • 谢谢@Constantin Beer。我不必添加您建议的行,但帮助我查看了我添加 const fetchOptions = { method: 'GET', mode: 'cors', }; 并在提取中使用的客户端:let res = await fetch(urlCloudFunc, fetchOptions); 它有效:)
    【解决方案2】:

    这里是完整的解决方案。我的问题是这里的客户端获取处理(fetchOptions),我使用了 no-cors。

    const [myFetchedHtml, setMyFetchedHtml] = useState('');
    const fetchOptions = {
        method: 'GET',
        mode: 'cors',
    };
    
    // Html Fetch via Google cloudFunction
      useEffect(() => fetch(urlCloudFuncPage3, fetchOptions)
        .then(res => res.text())
        .then((html) => {
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, 'text/html');
          const docDiv = doc.querySelector('div').innerHTML;
          return docDiv;
        })
        .then(docDiv => setMyFetchedHtml(docDiv))
        .catch((err) => {
          console.log('Failed to fetch: ', err);
        }), []);
    
      const createMarkup = () => ({ __html: myFetchedHtml });
    

    然后在组件渲染中使用它,返回如下:

    <div dangerouslySetInnerHTML={createMarkup()} />
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2017-11-02
      • 2022-12-09
      • 2022-01-01
      • 2012-04-13
      • 2019-05-04
      相关资源
      最近更新 更多