[英]Why doesn't d3.json send cookies with the request?
I'm new to doing ajax requests with the built-in methods in d3.js (v5). 我是使用d3.js(v5)中的内置方法进行ajax请求的新手。 Here's my code:
这是我的代码:
d3.json(uri).then(data =>console.log(data));
I tried this in an app that uses cookie authentication, and kept getting 401 status codes. 我在使用Cookie身份验证的应用程序中尝试了此操作,并不断获取401状态代码。 Using the chrome dev tools revealed that it's sending the request without any cookies at all.
使用chrome dev工具显示,它发送的请求完全没有任何cookie。
That's weird because ajax requests in native javascript send cookies along with every request by default. 这很奇怪,因为默认情况下,本机javascript中的ajax请求会与所有请求一起发送cookie。 Here's an example of an ajax request in native javascript:
这是原生javascript中的ajax请求示例:
function nativeAjax(uri, callback) {
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
callback(request);
}
}
request.open('get', uri, true);
request.send(null);
}
nativeAjax(uri, request => console.log(request.status));
Plugging this into my app, chrome dev tools shows it does send the authentication cookie along with the request and indeed the request.status
comes back as 200
showing that it is indeed authenticated. chrome dev工具将其插入我的应用程序,显示它确实将身份验证cookie与请求一起发送,并且实际上是
request.status
返回200
表明它确实已被身份验证。
My questions are: 我的问题是:
d3.json
to send the required cookie? d3.json
发送所需的cookie? Version 5 switched to use the Fetch API, which doesn't send any cookies by default. 版本5切换为使用Fetch API,该API默认情况下不发送任何cookie。 You can overcome this by adding options for d3.json to pass through to fetch:
您可以通过添加d3.json传递给fetch的选项来克服这一问题:
d3.json(uri, {credentials: "same-origin"}).then(...);
Or, for cross-origin requests: 或者,对于跨域请求:
d3.json(uri, {credentials: "include"}).then(...);
If a 4XX status (or 5XX) is returned D3 will cause the promise to reject, which you can handle by providing a second callback function to then
. 如果返回4xx状态(或5XX)D3将导致承诺拒绝,您可以通过提供第二个消息处理函数
then
。 I welcome corrections, but I believe there is no way within this function to get the actual status code. 我欢迎进行更正,但我相信此函数无法获取实际的状态代码。
The only mention of the change to Fetch and promises I found in the documentation (at the time of writing) was in the changelog: D3 v5 Changes . 我在文档中(在撰写本文时)仅发现了对Fetch和promises 所做的更改 ,该更改记录是在changelog中: D3 v5 Changes 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.