【问题标题】:react native fetch url for expo on web为 web 上的博览会反应原生获取 url
【发布时间】:2020-08-02 13:27:42
【问题描述】:

我使用此代码将我的 android 物理设备连接到服务器和 mongo db

const Url = "http://192.168.1.2:8080/"
fetch(Url, {
  method: "GET",
  mode: 'no-cors',
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(res=>res.json())
.then(response => console.log(response))
.catch(error => console.log(error));

如您所见,我可以使用 192.168.1.2 (IPv4) 将我的 android 物理设备连接到我的计算机和服务器。

但是当我在网络上使用"http://192.168.1.2:8080/""http://localhost:8080/" 时,它不起作用并给我这个控制台错误:

GET http://192.168.1.2:8080/ net::ERR_ABORTED 401 (Unauthorized)
SyntaxError: Unexpected end of input
    at App.js:34

如何解决这个问题?网络博览会的网址是什么?

【问题讨论】:

  • 你能展示你拥有的代码的一部分,其中抛出了这个异常吗?
  • App.js:34 是这一行代码:.then(res=>res.json())。需要全部功能码吗?

标签: react-native url fetch


【解决方案1】:

在网上搜索了一下,我找到了自己的解决方案

需要将mode: 'no-cors', 更改为mode: 'cors',

并且在 nodejs 服务器中需要添加此代码:

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'application/json,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多