不确定为什么我的 javascript FETCH 调用失败,当服务器 returns HttpStatus 200 OK

Unsure why my javascript FETCH call is failing, when the server returns HttpStatus 200 OK

我有一个 SPA 客户端应用程序正在对我的本地主机网络服务器执行 REST 调用。我正在使用 javascript 进行调用并使用 fetch() 进行调用。

我的响应是 HttpStatus 200(我可以单步执行我的网络服务器代码并通过查看 XHR request/responses 使用 Chrome 开发工具确认这一点)。

我正在执行 HTTP POST(到我的网络服务器) 响应是 Http 200 OK(不是 201 Created)。

在有人开始纠正我 POST 返回 200 之前 -> 这是一个 LOGIN/AUTHENTICATION 端点,因此是 200,而不是 201。

那么 - 有什么办法可以弄清楚为什么 fetch 会这样做吗?

更新:所以当我使用 Chrome 时,响应显示:Failed to load response data。但!如果我使用(程序)Postman 执行相同的 POST 然后我 do 得到一个响应主体...

这是我的代码..

export function authenticateUser(idToken) {

    var formData = new FormData();
    formData.append('idToken', idToken);

    fetch('https://localhost:44387/authentication',
            {
                method: 'POST',
                body: formData
            })
        .then(handleErrors)
        .then(response => console.log("ok"))
        .catch(error => console.log(error));
}

export function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

编辑#1:

编辑#2:

该死 - 答案是 CORS :: 我的网络服务器上没有 CORS 设置。

线索:

  • 使用 Postman 测试我的端点,它 100% 有效
  • @sideshowbarker 的评论建议我提问 CORS

快速 google 搜索让我找到了 this simple explanation:

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.


What is "Same Origin"?

Two URLs have the same origin if they have identical schemes, hosts, and ports. (RFC 6454) These two URLs have the same origin:

These URLs have different origins than the previous two:

所以在我的场景中我有:

那么差异是什么?

  • Scheme : http vs https <-- 不同
  • Host : localhost 对比 localhost <-- same/ok
  • Port : 3000 vs 44387 <-- 不同

所以这三个部分中至少有一个是差异的,所以我需要在我的后端启用 CORS

一旦我这样做了,一切正常:)