Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'

Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'

我尝试了对 REST-API 的 ReactJS 获取调用并想要处理响应。通话有效,我收到回复,我可以在 Chrome 开发工具中看到:

function getAllCourses() {
fetch('http://localhost:8080/course', {
    method: 'POST',
    mode: 'no-cors',
    credentials: 'same-origin',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        objectClass: 'course',
        crud: '2'
    })
}).then(function (response) {
    console.log(response);
    return response.json();

}).catch(function (err) {
    console.log(err)
});
}

当我尝试处理响应时,我在

处收到 "SyntaxError: Unexpected end of input"
return response.json();

console.log 看起来像这样:

我的回复 JSON 看起来像这样,它是有效的,我用 jsonlint 检查了它:

[
  {
    "0x1": {
      "users": [],
      "lectures": [],
      "owner": "0x2",
      "title": "WWI 14 SEA",
      "description": null,
      "objectClass": "course",
      "id": "course_00001"
    },
    "0x2": {
      "username": "system",
      "lectures": [],
      "course": null,
      "solutions": [],
      "exercises": [],
      "roles": [
        "0x3",
        "0x4",
        "0x5"
      ],
      "objectClass": "user",
      "id": "user_00001"
    },
    "0x3": {
      "roleName": "ROLE_ADMIN",
      "objectClass": "role",
      "id": "role_00001"
    },
    "0x4": {
      "roleName": "ROLE_STUDENT",
      "objectClass": "role",
      "id": "role_00002"
    },
    "0x5": {
      "roleName": "ROLE_DOCENT",
      "objectClass": "role",
      "id": "role_00003"
    }
  }
]

在您的 then 中,您应该在返回之前检查响应是否正常 response.json:

.then(function (response) {
    if (!response.ok) {
        return Promise.reject('some reason');
    }

    return response.json();

})

如果你想在被拒绝的承诺中包含错误信息,你可以这样做:

.then(function (response) {
    if (!response.ok) {
       return response.text().then(result => Promise.reject(new Error(result)));
    }

    return response.json();
})

您需要从请求中删除 mode: 'no-cors' 设置。设置 no-cors 模式正是您遇到问题的原因。

no-cors 请求的响应类型为 opaque。问题中的日志片段表明了这一点。 Opaque 表示您的前端 JavaScript 代码看不到响应 body 或 headers.

https://developer.mozilla.org/en-US/docs/Web/API/Request/mode 说明:

no-cors — JavaScript may not access any properties of the resulting Response

所以设置no-cors模式的效果本质上是告诉浏览器,“不要让前端JavaScript代码访问响应body或headers 在任何情况下。”

我想你正在尝试 no-cors 因为来自 http://localhost:8080/course 的响应不包括 Access-Control-Allow-Origin 响应 header 或者因为你的请求是一个触发CORS preflight,因此您的浏览器会进行 OPTIONS 预检。

但是使用no-cors模式并不能解决这些问题。解决方案是:

您可以通过在 php 的 header 或其他服务器端点中添加以下行来避免 CORS 策略的问题:

<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');

// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);

// Use $jsonObj
print_r($jsonObj->message);

...
// End php
?>

使用 POST 请求获取代码的模型是:

const data = {
        optPost: 'myAPI',
        message: 'We make a research of fetch'
    };
const endpoint = 'http://example.com/php/phpGetPost.php';

fetch(endpoint, {
    method: 'POST',
    body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
    console.info('fetch()', response);
    return response;
});

我知道这个答案可能来得太晚了,可能已经解决了,但我今天遇到了同样的问题,我只需要在 headers 散列的末尾添加一个“,”,然后我就停止了收到错误

export function addContacts(formData) {
  return(dispatch) => {
    dispatch({type: 'POSTING_CONTACTS'});
    console.log(formData)
    return fetch(uri, {
      method: 'POST',
      body: JSON.stringify({contact: {name: formData.name, phone_number: formData.phoneNumber}}),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
    })
    .then(response => {
        return response.json()
      }).then(responseJSON => {
        console.log(responseJSON)
        return dispatch({type: 'ADD_CONTACT', payload: responseJSON});
      })
  }
}     

只需复制以下代码并将其粘贴到 web.config 文件的 <system.webServer> 标签下。

<httpProtocol>  
    <customHeaders>  
     <add name="Access-Control-Allow-Origin" value="*" />  
     <add name="Access-Control-Allow-Headers" value="Content-Type" />  
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />  
    </customHeaders>  
  </httpProtocol>