Giter Club home page Giter Club logo

d3-request's Introduction

d3-request

This module is deprecated as of D3 5.0; please use d3-fetch instead.

This module provides a convenient alternative to XMLHttpRequest. For example, to load a text file:

d3.text("/path/to/file.txt", function(error, text) {
  if (error) throw error;
  console.log(text); // Hello, world!
});

To load and parse a CSV file:

d3.csv("/path/to/file.csv", function(error, data) {
  if (error) throw error;
  console.log(data); // [{"Hello": "world"}, …]
});

To post some query parameters:

d3.request("/path/to/resource")
    .header("X-Requested-With", "XMLHttpRequest")
    .header("Content-Type", "application/x-www-form-urlencoded")
    .post("a=2&b=3", callback);

This module has built-in support for parsing JSON, CSV and TSV; in browsers, but not in Node, HTML and XML are also supported. You can parse additional formats by using request or text directly.

Installing

If you use NPM, npm install d3-request. Otherwise, download the latest release. You can also load directly from d3js.org, either as a standalone library or as part of D3 4.0. AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3 global is exported:

<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script src="https://d3js.org/d3-request.v1.min.js"></script>
<script>

d3.csv("/path/to/file.csv", callback);

</script>

API Reference

# d3.request(url[, callback]) <>

Returns a new request for specified url. If no callback is specified, the returned request is not yet sent and can be further configured. If a callback is specified, it is equivalent to calling request.get immediately after construction:

d3.request(url)
    .get(callback);

If you wish to specify a request header or a mime type, you must not specify a callback to the constructor. Use request.header or request.mimeType followed by request.get instead. See d3.json, d3.csv, d3.tsv, d3.html and d3.xml for content-specific convenience constructors.

# request.header(name[, value]) <>

If value is specified, sets the request header with the specified name to the specified value and returns this request instance. If value is null, removes the request header with the specified name instead. If value is not specified, returns the current value of the request header with the specified name. Header names are case-insensitive.

Request headers can only be modified before the request is sent. Therefore, you cannot pass a callback to the request constructor if you wish to specify a header; use request.get or similar instead. For example:

d3.request(url)
    .header("Accept-Language", "en-US")
    .header("X-Requested-With", "XMLHttpRequest")
    .get(callback);

Note: this library does not set the X-Requested-With header to XMLHttpRequest by default. Some servers require this header to mitigate unwanted requests, but the presence of the header triggers CORS preflight checks; if necessary, set this header before sending the request.

# request.mimeType([type]) <>

If type is specified, sets the request mime type to the specified value and returns this request instance. If type is null, clears the current mime type (if any) instead. If type is not specified, returns the current mime type, which defaults to null. The mime type is used to both set the "Accept" request header and for overrideMimeType, where supported.

The request mime type can only be modified before the request is sent. Therefore, you cannot pass a callback to the request constructor if you wish to override the mime type; use request.get or similar instead. For example:

d3.request(url)
    .mimeType("text/csv")
    .get(callback);

# request.user([value]) <>

If value is specified, sets the user name for authentication to the specified string and returns this request instance. If value is not specified, returns the current user name, which defaults to null.

# request.password([value]) <>

If value is specified, sets the password for authentication to the specified string and returns this request instance. If value is not specified, returns the current password, which defaults to null.

# request.timeout([timeout]) <>

If timeout is specified, sets the timeout attribute of the request to the specified number of milliseconds and returns this request instance. If timeout is not specified, returns the current response timeout, which defaults to 0.

# request.responseType([type]) <>

If type is specified, sets the response type attribute of the request and returns this request instance. Typical values are: (the empty string), arraybuffer, blob, document, and text. If type is not specified, returns the current response type, which defaults to .

# request.response(value) <>

Sets the response value function to the specified function and returns this request instance. The response value function is used to map the response XMLHttpRequest object to a useful data value. See the convenience methods json and text for examples.

# request.get([data][, callback]) <>

Equivalent to request.send with the GET method:

request.send("GET", data, callback);

# request.post([data][, callback]) <>

Equivalent to request.send with the POST method:

request.send("POST", data, callback);

# request.send(method[, data][, callback]) <>

Issues this request using the specified method (such as GET or POST), optionally posting the specified data in the request body, and returns this request instance. If a callback is specified, the callback will be invoked asynchronously when the request succeeds or fails. The callback is invoked with two arguments: the error, if any, and the response value. The response value is undefined if an error occurs. This is equivalent to:

request
    .on("error", function(error) { callback(error); })
    .on("load", function(xhr) { callback(null, xhr); })
    .send(method, data);

If no callback is specified, then "load" and "error" listeners should be registered via request.on.

# request.abort() <>

Aborts this request, if it is currently in-flight, and returns this request instance. See XMLHttpRequest’s abort.

# request.on(type[, listener]) <>

If listener is specified, sets the event listener for the specified type and returns this request instance. If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. If listener is null, removes the current event listener for the specified type (if any) instead. If listener is not specified, returns the currently-assigned listener for the specified type, if any.

The type must be one of the following:

  • beforesend - to allow custom headers and the like to be set before the request is sent.
  • progress - to monitor the progress of the request.
  • load - when the request completes successfully.
  • error - when the request completes unsuccessfully; this includes 4xx and 5xx response codes.

To register multiple listeners for the same type, the type may be followed by an optional name, such as load.foo and load.bar. See d3-dispatch for details.

# d3.csv(url[[, row], callback]) <>

Returns a new request for the CSV file at the specified url with the default mime type text/csv. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/csv")
    .response(function(xhr) { return d3.csvParse(xhr.responseText, row); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/csv")
    .response(function(xhr) { return d3.csvParse(xhr.responseText, row); })
    .get(callback);

An optional row conversion function may be specified to map and filter row objects to a more-specific representation; see dsv.parse for details. For example:

function row(d) {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
}

The returned request exposes an additional request.row method as an alternative to passing the row conversion function to d3.csv, allowing you to configure the request before sending it. For example, this:

d3.csv(url, row, callback);

Is equivalent to this:

d3.csv(url)
    .row(row)
    .get(callback);

# d3.html(url[, callback]) <>

Returns a new request for the HTML file at the specified url with the default mime type text/html. The HTML file is returned as a document fragment. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/html")
    .response(function(xhr) { return document.createRange().createContextualFragment(xhr.responseText); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/html")
    .response(function(xhr) { return document.createRange().createContextualFragment(xhr.responseText); })
    .get(callback);

HTML parsing requires a global document and relies on DOM Ranges, which are not supported by JSDOM as of version 8.3; thus, this method is supported in browsers but not in Node.

# d3.json(url[, callback]) <>

Returns a new request to get the JSON file at the specified url with the default mime type application/json. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("application/json")
    .response(function(xhr) { return JSON.parse(xhr.responseText); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("application/json")
    .response(function(xhr) { return JSON.parse(xhr.responseText); })
    .get(callback);

# d3.text(url[, callback]) <>

Returns a new request to get the text file at the specified url with the default mime type text/plain. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/plain")
    .response(function(xhr) { return xhr.responseText; });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/plain")
    .response(function(xhr) { return xhr.responseText; })
    .get(callback);

# d3.tsv(url[[, row], callback]) <>

Returns a new request for a TSV file at the specified url with the default mime type text/tab-separated-values. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("text/tab-separated-values")
    .response(function(xhr) { return d3.tsvParse(xhr.responseText, row); });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("text/tab-separated-values")
    .response(function(xhr) { return d3.tsvParse(xhr.responseText, row); })
    .get(callback);

An optional row conversion function may be specified to map and filter row objects to a more-specific representation; see dsv.parse for details. For example:

function row(d) {
  return {
    year: new Date(+d.Year, 0, 1), // convert "Year" column to Date
    make: d.Make,
    model: d.Model,
    length: +d.Length // convert "Length" column to number
  };
}

The returned request exposes an additional request.row method as an alternative to passing the row conversion function to d3.tsv, allowing you to configure the request before sending it. For example, this:

d3.tsv(url, row, callback);

Is equivalent to this:

d3.tsv(url)
    .row(row)
    .get(callback);

# d3.xml(url[, callback]) <>

Returns a new request to get the XML file at the specified url with the default mime type application/xml. If no callback is specified, this is equivalent to:

d3.request(url)
    .mimeType("application/xml")
    .response(function(xhr) { return xhr.responseXML; });

If a callback is specified, a GET request is sent, making it equivalent to:

d3.request(url)
    .mimeType("application/xml")
    .response(function(xhr) { return xhr.responseXML; })
    .get(callback);

XML parsing relies on xhr.responseXML which is not supported by node-XMLHttpRequest as of version 1.8; thus, this method is supported in browsers but not in Node.

d3-request's People

Contributors

mbostock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

d3-request's Issues

Failing tests and crashing since 0.2.0

Hi,

I've noticed that the package fails 10/82 tests in versions 0.2.0, 0.2.1 and 0.2.2.
However, more severely, it also seems to crash the npm republish script.

I tried to debug it but the error message is very vague. Here is the error log I received.

Hope that helps and keep up the good work on v4.0!

XMLHttpRequest is not defined

Hi, this script:

var d3 = require('d3');
d3.json('https://nodejs.org/api/all.json', function(err, json) {})

returns:

/path/to/node_modules/d3/build/d3.js:4438
          xhr = new XMLHttpRequest,
                    ^
ReferenceError: XMLHttpRequest is not defined
    at request (/path/to/node_modules/d3/build/d3.js:4438:18)

"Node child_process module not supported in browsers" error after upgrade [email protected] to @4.10.2

HTTP Basic Authentication credentials in Google Chrome 64 not transfered to AJAX calls

Our project is protected by a HTTP Basic Authentication and we have to enter the username/password on every d3.json() call in Google Chrome.

It seems like in Google Chrome 64 there is a difference between xhr.open(method, url, true, user, password); with user=null and password=null and xhr.open(method, url, true);. In the second case http://mydomain is built as URL and the credentials from the browser cache are submitted and everything is fine. But in the first case a URL like http://null:null@mydomain is build which overwrites the cached credentials. And because the credentials are wrong the browser gives you the authenticate popup. You can see the URLs in the browser's developer toolbar in the network tab.

xhr.open(method, url, true, user, password);

Latest Chrome version(?) doesn't accept null for user:password in xhr.send

In this issue I'm using the latest D3 version 4 from the d3js.org site.

With the following code snippet (and with other similar d3-requests):

d3.json("stateslatlontopo.json")
.get(function(error, us) {
if (error) throw error;
svg.selectAll('.states')
.data(topojson.feature(us, us.objects.stateslatlon).features)
.enter()
.append('path')
.attr('class', 'states')
.attr('d', path)
});

Chrome throws the following error:

d3.v4.js:11472 GET https://null:null@(web site base address)/stateslatlontopo.json 401 (Authorization Required)

I checked the d3 code and saw the defaults for user and password are set to null. After reading the d3-request doc, saw that setting user and password to empty string ('') will pass along the user's id and password in the request. And upon adding .user('').password('') after the d3.json, the page worked as it had previously without having to add those. However, adding .user and .password is not needed in order to view the page in Firefox. Just to note, there's no cross origin here as the JSON file is in the same directory as the web page.

Also note that this is occurring on a web server where users login with user id and password maintained by a Lightweight Directory Access Protocol (LDAP). So that may come into play. However, this issue is appearing on Chrome Version 64.0.3282.186 (Official Build) (32-bit) (which may have recently been updated) and not Firefox Quantum build 58.0.2 (32-bit). I had just demonstrated the page I was working on last week without the need for the .user and .password. Hence why I'm suspecting that a Chrome update may be causing this issue where null:null for userid and password no longer work when a user logins in to view a website. I also removed the .user and .password from the request and retested this on a web severer where I didn't have to log in and used Chrome. This also worked as expected with no error. In that case, the following displayed in the Network and Headers tab in the Chrome debugger:

Request URL:https://null:null@(web page address)/stateslatlontopo.json
Request Method:GET
Status Code:200 OK

However, when I have to log into the other server and using Chrome:

Request URL:https://null:null@(web page address)/stateslatlontopo.json
Request Method:GET
Status Code:401 Authorization Required

In Firefox, the Request URL does not show the "null:null@" before the web page address when I view it on the Network tab either using the .user and .password or not.

So, I believe this may be due to a change in Chrome where null for user id and password is not valid where a user has to log in first in order to view the pages. At least I discovered that adding the user and password options with empty strings still allowed the request and the page to function normally.

I know d3-request will be deprecated in version 5 for d3-fetch and this only seems to affect the latest Chrome version where a user has to log in. So perhaps this won't be an issue in the near future. But thought I should bring it to your attention should others have a similar issue and that the work around would be to add the .user('').password('') to the request.

import statement not working

Issue #16 was closed and I cannot re-open despite the possibility that this is a real issue in d3-request.

import * as d3select from 'd3-selection';
import * as d3request from 'd3-request';

var mysvg = d3select.select("#mysvg"); //works
var request = d3request.xml('assets/emojis/laughing.svg'); //doesnt work

Why would d3-select work correctly and d3-request loading from UMD module?
I'm using the standard ionic bundler via rollup https://github.com/driftyco/ionic-app-scripts/blob/master/config/rollup.config.js

My package.json is consistent between the 2 packages, which leads me to believe the problem is in d3-request:

"dependencies": {
"d3-request": "^1.0.2",
"d3-selection": "^1.0.2",
...
},
"devDependencies": {
"typescript": "^2.0.3",
"@types/d3-request": "^1.0.1",
"@types/d3-selection": "^1.0.5",
"@ionic/app-scripts": "latest"
},

Version 1.0.6 breaks build because of XmlHtppRequest dependency

Webpack fails with the error Module not found: Error: Cannot resolve module 'child_process'.
child_process is required in XMLHttpRequest.

I resolved this by adding XMLHttpRequest to my Webpack externals, but seems like I shouldn't have to do that.

externals:[{
    xmlhttprequest: '{XMLHttpRequest:XMLHttpRequest}'
}]

child_process cannot be used in the browser - why is is needed?

Electron compatibility

I am not sure if this is an electron issue or a d3 issue (or maybe just user error). However, since it works with an older version of d3 but not the latest, I am routing it here. I do not know

d3 version 4.12 (d3-request 1.0.6) does not work well with electron. In particular, I cannot access local files by relative address, for example d3.csv("data.csv")

I found that, if I comment line 3 in d3-request/builds/d3-request.node.js
//var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
it uses the built-in electron XMLHttpRequest and then works.

When I run an earlier version of d3 (version 3.5.17), which does not have any d3-request module, this issue does not occur and d3.csv("data.csv") succeed

Thank you for the packages.

index.html:
`

<script> d3 = require("d3"); d3.csv("data.csv", function(data){ console.log(data); }, function(error, rows){ console.log(rows); }) </script> `

package.json (works):
{ "name": "simple", "version": "0.1.0", "main": "./main.js", "scripts": { "start": "electron .", "binary": { "module_name": "simple", "module_path": "./lib/binding/", "host": "localhost" } }, "dependencies": { "electron-prebuilt": "", "electron-debug": "", "d3": "^3.5.6" } }

package.json (fails):
{ "name": "simple", "version": "0.1.0", "main": "./main.js", "scripts": { "start": "electron .", "binary": { "module_name": "simple", "module_path": "./lib/binding/", "host": "localhost" } }, "dependencies": { "electron-prebuilt": "", "electron-debug": "", "d3": "" } }

d3.Js request giving Method not allowed error (405)

I am trying to request an URL with the headers, below is the request,

d3.json('http://localhost:64453/v4/Production/Dashboard/YieldByLine')
.header("application_key", "aa")
.header("lab_code", "aa")
.get(function (error, data) {
if (error) {
console.log(error);
} else {
console.log(data);
}
});

It is giving me an error (Method not allowed 405 - Response for preflight has invalid HTTP status code 405).

I have enabled the CORS in my API as well. Still, I am getting the issue.

I have tried to execute this in POSTMAN and it is giving me the proper result with this header.

Can anyone please help me to resolve this issue?

Thanks,
Bhargava

Expose XHR status on error

Hi.

When I get a 404 response, the "error" event that's fired only includes an XHR ProgressEvent (in Chrome), and nothing else. That would be this code path.

This isn't too helpful, and I was wondering if you could expose the xhr.status or more details of the underlying XHR itself. Perhaps either as an extra part of the error payload, or similarly to how you allow the user access to the XHR on the request.response(fn) method.

I like that I can do

.response(function(xhr) { /* do something with xhr.responseText */ })

So on an error I want to

.errorResponse(function(xhr) { /* check xhr.status or xhr.getAllResponseHeaders() */ })

Thanks!
And thanks for the amazing software. You rock!

d3.html throws `document is not defined` in Node.js

This code

// npm install --save d3@next
var d3 = require('d3')
d3.html('https://foo.org/', function(err, documentFragment) {
  if (err) throw err;
  parseDoc(d3.select(documentFragment))
})

function parseDoc(doc) {
  console.log(doc.selectAll('span'));
}

throws

ReferenceError: document is not defined

as indeed in Node.js document is not defined in src/html.js

Last publish breaks webpack build.

It seems that the last publish of this commit d635b89 broke d3 for the browser. I have an angular 1.5 app that uses d3 and since d3 was updated to require 1.0.6 of this package, I get this error when trying to load the app after building:


XMLHttpRequest.js:15 Uncaught Error: Cannot find module "child_process"
    at webpackMissingModule (XMLHttpRequest.js:15)
    at Object.eval (XMLHttpRequest.js:15)
    at eval (XMLHttpRequest.js:622)
    at Object.<anonymous> (bundle.js?version=13.1.3:10487)
    at __webpack_require__ (bundle.js?version=13.1.3:20)
    at eval (d3-request.node.js:3)
    at Object.<anonymous> (bundle.js?version=13.1.3:10481)
    at __webpack_require__ (bundle.js?version=13.1.3:20)
    at eval (d3.node.js:25)
    at Object.<anonymous> (bundle.js?version=13.1.3:10343)
    at __webpack_require__ (bundle.js?version=13.1.3:20)
    at eval (dashboard.timelines.controller.js:26)
    at Object.<anonymous> (bundle.js?version=13.1.3:10319)
    at __webpack_require__ (bundle.js?version=13.1.3:20)
    at eval (dashboard.timelines.directive.js:14)
    at Object.<anonymous> (bundle.js?version=13.1.3:10295)

I have not been able to figure out which dependency update in the commit is causing this yet, but I figured I'd post this first. Reverting to d3 4.10.0 is a temporary workaround, since it requires 1.0.5 of d3-request.

d3.request is not a function

I find d3.request in the API document but when I write this code in my project, there raise the error about 'd3.request is not a function'

Problem with requesting local files?

I have noticed issues with using d3.request since moving my repository from D3 version 4.10.0 to version 4.10.2.

By examining my package-lock.json, I noticed one difference is that the former uses d3-request version 1.0.5 whereas the latter uses d3-request version 1.0.6.

The situation:

  • I am using browserify and http-server to prepare and serve my file respectively.
  • I have a file called index.html which I access via localhost:8080 when I'm building something.
  • I have a file called filelist.json which I can access via localhost:8080/filelist.json while I'm building.
  • I tried using d3.json() to access filelist.json from index.html and process the data.
  • Initially I used error and data arguments in the d3.json() callback to throw any errors and start working with the data. However, I got an Unexpected token T at character 0 error.
  • I removed the error throw and simply logged data in the console. This is when I saw that the T was the beginning of the line TypeError which was reporting that it could not access the file.
  • The problem seems to be that d3.json() was attempting to access my file from the address localhost:80filelist.json, instead of the full and correct address.
  • I tried this with other d3-request methods, like d3.tsv() and d3.request() itself. Same error thrown, albeit in slightly different guises depending on the function.

Since rolling back to D3 v4.10.0 I have not had this problem.

Basic authentication?

See d3/d3#2131. These need to be passed to XMLHttpRequest.open.

We also need to expose the withCredentials flag (for cookie-based authentication?)—although at least now you can use the "beforesend" event to set it, I think. This should be separate from specifying a username and password, though.

Loading d3-request via HTML versus a Node Module Produces Different Results

When loading d3-request via html <script src="node_modules/d3/build/d3.js" type="text/javascript"></script> d3.tsv works as described in the API documentation. For example the following code is in a node application and uses d3 without any further import/require statement.

d3.tsv("data.tsv", function(error, data) {
  if (error) throw error;
  console.log(data);
}

And loads data into the variable data as expected.

When d3 is loaded in a script or via a node terminal (REPL) via let d3 = require('d3');, such as in the following,

let d3 = require('d3');

d3.tsv("data.tsv", function(error, data) {
  if (error) throw error;
  console.log(data);
}

without d3 being defined in the html ahead of time, the variable data ends up being a three object array, where all objects contain Error: connect ECONNREFUSED 127.0.0.1:80

Disclaimer: This problem came about using D3 as a component in an Electron application. This very well may not be an issue with D3 but it'd be helpful to understand why it works one way and not the other.

How about adding d3.image for loading images?

If you want to pre-load images for use in canvas, you have to do this

var imageObj = new Image();
imageObj.onload = function() {
     // do sth, e.g.
     context.drawImage(this, 0, 0);
};
imageObj.src = url;

d3-request could abstract this, so I can load images in a queue etc

d3.image(url, function(err, img) {
    context.drawImage(img, 0,0);
});

Unable to get xhr.status

I don't believe its possible to get the status code within the on("error", ...) callback?
Might be nice to have full access to the xhr object?

import statement not working

I'm having this issue here http://stackoverflow.com/q/39909200/1267778 where a simple import statement does not work for d3-request.

import * as d3select from 'd3-selection';
import * as d3request from 'd3-request';

var mysvg = d3select.select("#mysvg"); //works
var request = d3request.xml('assets/emojis/laughing.svg'); //doesnt work

The d3select call gets properly compiled to the exported "select" function. However the resulting code for the second line compiles to something like:

var d3Request$1 = unwrapExports(d3Request);

var d3Request$2 = Object.freeze({
    default: d3Request$1,
    __moduleExports: d3Request
});

And then tries to call d3Request$2.xml, which doesn't exist.

request.get takes data argument?

I think this might be unintentional, but request.get is currently implemented as:

d3.request.prototype.get = function(data, callback) {
  return request.send("GET", data, callback);
};

When according to the documentation, it should probably be implemented as:

d3.request.prototype.get = function(callback) {
  return request.send("GET", null, callback);
};

Alternatively, the type-helper should be changed to more safely pass callback only if it is a function, i.e., to change this:

export default function(defaultMimeType, response) {
  return function(url, callback) {
    var r = request(url).mimeType(defaultMimeType).response(response);
    return callback ? r.get(callback) : r;
  };
}

To this:

export default function(defaultMimeType, response) {
  return function(url, callback) {
    var r = request(url).mimeType(defaultMimeType).response(response);
    return typeof callback === "function" ? r.get(callback) : r;
  };
}

Otherwise, if callback is not a function, it will instead be sent as data with the GET request, which is surely unintended.

Related d3/d3#2896.

d3.request inherent uri encoding not handling encoding % itself correctly?

It seems perhaps d3.request inherent uri encoding is not handle % correctly?

for example if I use d3.request to pass a text string in a parameter string that includes a % character it is not encoded so 20% . becomes 20%%20. rather than 20%25%20. and fails later...

I understand the answer may be to wrap in encodeURIComponent() but putting that all over the place seems not optimal since things get encoded anyway...

please evaluate and advise.

thanks!

JCS

default port on localhost

When I'm running a server on localhost on some port, say 3000, and use d3-request to reference a file from the root url, e.g.

const d3 = require('d3-request');
d3.json('/my-data.json', ...)

this sends a GET request to http://localhost/my-data.json, while I'd expect it to be routed to http://localhost:3000/my-data.json. To be clear the javascript and html is loading from localhost:3000 as well in this case.

Using superagent or this ajax snippet from SO I can request /my-data.json and it is fetched correctly.

Rename to d3-request.

[Edit: The old title was “why not rename to d3.req or d3.request?”]

I kind of don't like the name "xhr". It feels so stupid to still carry on the XML roots, in a time where virtually no XML documents are being requested any more.

Let's go for d3.req or d3.request instead.

d3.req.json('...', function() { .. })

Relative URLs falling back to "localhost" and no port instead of the window.location.host/port in v1.0.6 -- Browserify build

As of 1.0.6, requesting a relative URL no longer seems to work correctly. At least this is the case when building with Browserify...

For example, if I'm hosting a dev site at: http://mydevsite:8888 and try something like d3.csv('/data.csv') a request will be made to http://localhost/data.csv instead of http://mydevsite:8888/data.csv'.

Steps to reproduce:

  1. npm install -g browserify
  2. In a clean folder, create an index.html file:
<html>
  <head>
    <script src="/generated.js"></script>
  </head>
  <body></body>
</html>
  1. Create an index.js file:
const {csv} = require('d3-request');
csv('/test.csv', console.log);
  1. Create a sample test.csv file

  2. npm install [email protected]

  3. browserify index.js -o generated.js

  4. python -m SimpleHTTPServer 8888

  5. Open up in a browser (use http://127.0.0.1:8888) and verify that the csv file is properly requested at http://127.0.0.1:8888/test.csv

  6. Next: npm install [email protected] and repeat steps 6-8

  7. See that the the requested path is: http://localhost/test.csv

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.