首页 > 解决方案 > React 如何在发送 fetch 请求时避免错误?

问题描述

我正在尝试发送获取请求。

面临一些CORS错误,设置模式后:'no-cors',

请求已发送,http 状态码为 200,但在尝试获取响应时,控制台中出现错误:

Unhandled Rejection (SyntaxError): Unexpected end of input. Server headers are set in both files. 

请告诉我如何解决此错误?

api-本地/身份验证:

索引.php

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');

require "connect.php";
require "functions.php";

$type = $_GET['q'];

if($type === 'dict') {
  getDict($db);
  }

if($type === 'auth') {
  postAuth();
}

?>

登录.php

?php

 header("Access-Control-Allow-Origin: *");
 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");

include_once 'config/database.php';
include_once 'objects/user.php';
...

本地主机:3000:

动作.js

 fetch(`http://api-local/auth`, {
        method: 'POST',
        mode: 'no-cors',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({ "email": `${email}`, "password": `${pass}`})
    })
        .then(response => response.json())
        .then(response => console.log(response ));
    ```

标签: phpreactjsapifetch

解决方案


推荐阅读