【问题标题】:React Native - I can't get a response from my FETCH, but my api does get the data i postReact Native - 我无法从我的 FETCH 获得响应,但我的 api 确实获得了我发布的数据
【发布时间】:2021-01-04 20:34:56
【问题描述】:

我尝试了很多东西,它只会在它有“mode: no-cors”并且没有标题时才发布到 api。

我现在正在尝试使用 mode: 'cors',因为我读到出于安全原因我不应该使用 'no-cors'。但是,我必须删除标题,否则它不会发布数据。

代码如下:

signUp: async(email, password)=> {
  
  let values = {
    firstname: "pruebaNombre",
    lastname: "pruebaApellido",
    email: email,
    password: password
  }
  const config = {
    method: 'POST',
    mode: 'cors',
    // headers: { 
    //   'Access-Control-Allow-Origin':'*',
    //   'Content-Type': 'application/json' 
    // },
    body: JSON.stringify(values),
  }
  const response = await fetch('http://localhost/rest-api-authentication-example/API/create_user.php', config);
  const data = await response.json();
  console.log(data);   
}

console.log(data) 应该是带有“用户已创建”消息的 json,但我收到以下错误:

CORS 策略已阻止从源“http://localhost:19006”获取“http://localhost/rest-api-authentication-example/API/create_user.php”的访问权限:“访问- Control-Allow-Origin 标头的值 'http://localhost/rest-api-authentication-example/' 不等于提供的来源。让服务器发送带有有效值的标头,或者,如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

加载资源失败:net::ERR_FAILED

Uncaught (in promise) TypeError: Failed to fetch

数据确实发布在我的服务器上,但我无法从获取中获得响应。

已编辑。- 这些是我的服务器端的标头:

header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");

header("Content-Type: application/json; charset=UTF-8");

header("Access-Control-Allow-Methods: POST");

header("Access-Control-Max-Age: 3600");

header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

【问题讨论】:

  • 您能否更新您的问题以将您的 CORS 配置包含在您的服务器中
  • @rantao 好的,我刚刚编辑了它

标签: javascript reactjs fetch


【解决方案1】:

“Access-Control-Allow-Origin”标头的值“http://localhost/rest-api-authentication-example/”不等于提供的来源

尝试将 proxy: "http://localhost:${PORT}" 添加到您的 React-Native package.json 其中 PORT 是您的服务器端口

【讨论】:

  • 对不起,我有点迷路了。我应该在哪里声明变量 PORT?而且,我在使用 fetch 时还会使用相同的 url 吗?
  • 嘿!我刚刚通过将标题更改为: header("Access-Control-Allow-Origin: *");这会是一个很好的解决方案吗?因为它现在可以工作了:)
  • 出于开发目的,这很好,但我不建议将其用于生产应用程序。更改为 * 本质上是让任何人/域向您的服务器发出请求,这是一个安全风险
  • PORT 只是您服务器的端口号,例如,如果您的服务器端口是3001,那么它将是proxy: "http://localhost:3001
  • 谢谢!稍后将不得不更改它,现在我只是想让它工作哈哈
猜你喜欢
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 2017-05-02
相关资源
最近更新 更多