由于预检请求,获取答案为空吗?

huangapple go评论106阅读模式
英文:

Fetch answer empty due to the preflight?

问题

我有一个使用React.js / Redux / Webpack / ES6的Web应用程序,以及一个使用Gorilla的mux库的Go API。
当我使用下面的函数进行调用时,我的头部和内容都是空的。

我在我的Web应用程序中使用了这个包来进行调用:

"isomorphic-fetch": "^2.2.1",

我的调用示例:

export function Login(userData) {
return dispatch => {
fetch(API + '/login', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userData.email,
password: userData.password,
}),
})
.then(response => {
console.log(response);
console.log(response.statusText);
console.log(response.status);
console.log(response.headers);
console.log(response.headers.get("Authorization"));
console.log(response.json());
return response.json()
if (response.status >= 200 && response.status < 300) {
console.log(response);
dispatch(LoginSuccess(response));
} else {
const error = new Error(response.statusText);
error.response = response;
dispatch(LoginError(error));
throw error;
}
}).then(function(json) {
console.log('parsed json' + json)
})
.catch(error => { console.log('request failed', error); });
}
}

一开始我遇到了跨域问题https://stackoverflow.com/questions/22972066/how-to-handle-preflight-cors-requests-on-a-go-server,我使用了这个解决方案。

我们可以在控制台中查看调用:

login OPTIONS 200 fetch auths.actions.js:38 352 B 1 ms
login POST 200 json Other 567 B 82 ms

当我查看我的POST头部响应时,我得到:

HTTP/1.1 200 OK
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NTQ3NTcxNjEsInVzZXJfaWQiOiI1NmI1YjZlOTFhZTMzYjAwMDFhYmE1MTQifQ.WGoTMxm6OuN24Olwr93J3pND9dFLCtG5MyiRbqLWeD244JtDzq0bGgQMixeZxyuxwGK3u8KhyWD7Rr6iZAGNpA
Content-Type: application/json
Date: Sat, 06 Feb 2016 11:12:41 GMT
Content-Length: 2

所以响应处理了我的预检请求信息而不是我的POST请求?因为在response.headersresponse.headers.get("Authorization")中没有任何内容。
有什么问题吗?

英文:

I have an webapp react.js / redux / webpackt / es6... and an api in go with mux from gorilla.
When I make call with the function below my header is empty and content too.

I'm using this package in my webapp to make calls

&quot;isomorphic-fetch&quot;: &quot;^2.2.1&quot;,

My call example

export function Login(userData) {
  return dispatch =&gt; {
    fetch(API + &#39;/login&#39;, {
      method: &#39;post&#39;,
      headers: {
        &#39;Accept&#39;: &#39;application/json&#39;,
        &#39;Content-Type&#39;: &#39;application/json&#39;,
      },
      body: JSON.stringify({
        email: userData.email,
        password: userData.password,
      }),
    })
    .then(response =&gt; {
      console.log(response);
      console.log(response.statusText);
      console.log(response.status);
      console.log(response.headers);
      console.log(response.headers.get(&quot;Authorization&quot;));
      console.log(response.json());
      return response.json()
      if (response.status &gt;= 200 &amp;&amp; response.status &lt; 300) {
        console.log(response);
        dispatch(LoginSuccess(response));
      } else {
        const error = new Error(response.statusText);
        error.response = response;
        dispatch(LoginError(error));
        throw error;
      }
    }).then(function(json) {
      console.log(&#39;parsed json&#39; + json)
    })
    .catch(error =&gt; { console.log(&#39;request failed&#39;, error); });
  }

In the beginning I had a problem with cors https://stackoverflow.com/questions/22972066/how-to-handle-preflight-cors-requests-on-a-go-server I used this solution

We can look the call inside of the console :

login	OPTIONS	  200	fetch	auths.actions.js:38	352 B	1 ms	
login	POST	  200	json	Other	567 B	82 ms

When I look inside of my POST Header response I have :

HTTP/1.1 200 OK
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NTQ3NTcxNjEsInVzZXJfaWQiOiI1NmI1YjZlOTFhZTMzYjAwMDFhYmE1MTQifQ.WGoTMxm6OuN24Olwr93J3pND9dFLCtG5MyiRbqLWeD244JtDzq0bGgQMixeZxyuxwGK3u8KhyWD7Rr6iZAGNpA
Content-Type: application/json
Date: Sat, 06 Feb 2016 11:12:41 GMT
Content-Length: 2

So the response handle my preflight information not my POST ? Because there is nothing inside of the response.headers and response.headers.get(&quot;Authorization&quot;)
There is something wrong ?

答案1

得分: 11

我遇到了一个问题,我的请求头已经被正确发送和接收(Chrome的网络选项卡正确显示了所有发送的请求头),但是我无法在JavaScript中访问它们(response.headers为空)。根据https://stackoverflow.com/questions/32127369/fetch-get-request-returns-empty-headers中的描述,这是因为服务器没有设置Access-Control-Expose-Headers头,导致所需的头部无法暴露给JavaScript。

所以解决方案是在服务器上添加这个头部,然后就可以在JavaScript中访问这些头部了:

Access-Control-Expose-Headers: <header-name>, <header-name>, ...

该头部接受一个逗号分隔的头部名称列表,用于向浏览器暴露。

关于为什么需要这个头部的更多信息,请参见https://stackoverflow.com/questions/25673089/why-is-access-control-expose-headers-needed。

英文:

I had the problem that my headers were sent, correctly received (chrome's network tab correctly shows me all the sent headers), but I couldn't access them in js (response.headers was empty). As described in https://stackoverflow.com/questions/32127369/fetch-get-request-returns-empty-headers, this happened because the server did not set the Access-Control-Expose-Headers header, resulting in the needed headers not to be exposed to js.
So the solution is to add this header on the server and voilà, now the headers are accessible in js:

Access-Control-Expose-Headers: &lt;header-name&gt;, &lt;header-name&gt;, ...

The header takes a comma-separated list of header-names to be exposed to the browser.

For additional info on why this header is needed, see https://stackoverflow.com/questions/25673089/why-is-access-control-expose-headers-needed

1: https://stackoverflow.com/questions/35240520/fetch-answer-empty-due-to-the-preflight#comment58341226_35240520 "this link"

huangapple
  • 本文由 发表于 2016年2月6日 19:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/35240520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定