【问题标题】:Need to retrieve html from axios request需要从 axios 请求中检索 html
【发布时间】:2021-12-29 15:15:44
【问题描述】:

我正在使用 axios 向在后端公开 html 的资源发送请求。当我发送 GET 请求时,我收到一个对象作为响应。当我使用 console.log() 打印响应时,由于响应是一个对象而不是我期望的 html,它会破坏 React 应用程序。

目前我正在尝试在配置中指定 responseType: 'document'。但这似乎不起作用。我仍然得到一个错误的对象:

“错误:对象作为 React 子对象无效(找到:[object 承诺])。如果您打算渲染一组孩子,请使用 数组。”

最终我需要得到一个 <div></div>,我可以将它嵌入到我的 React 页面中。

import axios from 'axios';

const examplePage = "example.com/example"

export const requestExamplePage = async () => {
    const {data} = await axios.get(examplePage, {responseType: 'document})
    
    return data
}

【问题讨论】:

  • 你的问题是什么?
  • 对不起,我是新来发帖的。给我一点时间来弄清楚这是如何工作的,以便我可以编辑这个问题。
  • 完整添加您的代码,并且对问题也非常清楚。展示你的研究和你尝试过的 coe。
  • 我希望这很清楚
  • 刚刚编辑了错误的帖子

标签: javascript html reactjs axios get


【解决方案1】:

错误:

"Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."

实际上意味着您正在尝试兑现承诺。你确定那是解构请求的正确方法吗? data 必须是用双引号(字符串)包裹的 html,您还需要 dangerouslySetInnerHtml 将其注入到 div 中。

试试这个:

export const requestExamplePage = async () => {
    const {data} = await axios.get(examplePage, {responseType: 'document'})
    
    return (
        <div dangerouslySetInnerHTML={{ __html: data }} />
    )
}

确保数据是一个实际的 html 字符串。

【讨论】:

  • 谢谢。危险的SetInnerHTML 部分让它工作。另外,我需要将 responseType 设置为“text”。
猜你喜欢
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2016-07-31
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多