获取 someUrl.html 在 React Native / Expo 中不起作用?

Ska*_*Ska 4 fetch react-native expo

我正在尝试使用 fetch 来获取 React Native 中 HTML 页面的内容,并且我正在 expo 上运行它,在这里:

\n\n

https://snack.expo.io/@abalja/hellofetch

\n\n

基本上,代码没什么特别的,使用“fetch”,它确实适用于加载 .json 文件,但我无法让它适用于 .html 文件。它只是默默地失败了,我什至没有记录错误。我不确定这是 Expo 还是 ReactNative 问题。

\n\n
const url2 = \'http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html#ref=rss\'\n\nexport default class App extends React.Component {\n  componentDidMount(){\n\n    console.log(\'did mount, fetching: \' + url2)\n    fetch(url2)\n        .then((response) => {\n          console.log(response) // 1\n          return response.text()\n        })\n        .then((responseText) => {\n          console.log(\'fetch text\', responseText) // 2\n          // return responseText.movies;\n        })\n        .catch((error) => {\n          console.error(error);\n        });\n  }\n  render() {\n    return (\n      <View style={styles.container}>\n\n      </View>\n    );\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 1 处,我收到记录的响应:

\n\n
{type:"default",status:200,ok:true,headers:{\xe2\x80\xa6},url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html",_bodyInit:{\xe2\x80\xa6},_bodyBlob:{\xe2\x80\xa6}}\ntype:"default"\nstatus:200\nok:true\n\xe2\x96\xbaheaders:{map:{\xe2\x80\xa6}}\nurl:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html"\n\xe2\x96\xba_bodyInit:{_data:{\xe2\x80\xa6}}\n\xe2\x96\xba_bodyBlob:{_data:{\xe2\x80\xa6}}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 2 处,我完全没有记录任何内容。

\n

小智 5

Promise 语法让我很困惑,所以我改为 async-await:

async componentDidMount() {
    console.log('did mount, fetching: ' + url2);
    try {
        let response = await fetch(url2);
        let text = await response.text();
        console.log(text)
   } catch(e) {
        console.log(e)
   }
}
Run Code Online (Sandbox Code Playgroud)

有用!您可以在这里查看: https: //snack.expo.io/@aazwar/fetch-url