简体   繁体   English

反应本机获取数据

[英]React native fetch data

I have a problem with fetch data.我在获取数据时遇到问题。 My friend creates Rest Api.我的朋友创建了 Rest Api。 There is my fun:有我的乐趣:

const AnyCors = `https://cors-anywhere.herokuapp.com/`;
const urlAllBus = `http://207.185.72.111:15430/stops?size=15`;
    fetchBusStop = () => {
  return new Promise((resolve, rejects) => {
    fetch(AnyCors+urlAllBus)
      .then((result) => {
        if (!result.ok) throw result.json();
        return result.json();
      })
      .then((result) => {
        console.log(result);
        resolve(result);
      })
      .catch((error) =>
        error.then((body) => {
          console.log('Bad', body);
          rejects(body);
        }),
      );
  });
};

I create an app with react-native.我用 react-native 创建了一个应用程序。 When I use only urlAllBus my virtual machine work fine.当我只使用 urlAllBus 时,我的虚拟机工作正常。 The problem is with a physical machine.问题出在物理机上。 When I try using my fun with urlAllbus in chrome I get a problem with CORS so I used AnyCors+urlAllBus and everything works fine.当我尝试在 chrome 中使用 urlAllbus 时,我遇到了 CORS 问题,所以我使用了 AnyCors+urlAllBus,一切正常。 But in the virtual and physical machine there solutions not work.但是在虚拟机和物理机中,解决方案不起作用。 I don't know what I should do我不知道我应该做什么

You friend's API should accept CORS by adding a Access-Control-Allow-Origin: * header to its responses to allow any website to access it.您朋友的 API 应该通过在其响应中添加Access-Control-Allow-Origin: *标头以允许任何网站访问它来接受 CORS。 They can also limit access to a specific site by setting the header to the base URL of such site, like Access-Control-Allow-Origin: http://example.com .他们还可以通过将标头设置为此类站点的基本 URL 来限制对特定站点的Access-Control-Allow-Origin: http://example.com ,例如Access-Control-Allow-Origin: http://example.com

If the API is express-based, I hightly recommend the cors package for the job, as it makes it a single-line change.如果 API 是基于 express 的,我强烈推荐使用cors包来完成这项工作,因为它是单行更改。

Otherwise, tell them to give this MDN page a read for more information about CORS :)否则,告诉他们阅读此 MDN 页面以了解有关 CORS 的更多信息:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM