diff --git a/README.md b/README.md index 6bd4cf6ce..4492bb695 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,21 @@ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]" ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods "[\"PUT\", \"POST\", \"GET\"]" ``` +### Custom Headers + +If you wish to send custom headers with each request made by this library, for example, the Authorization header. You can use the config to do so: + +``` +const ipfs = IpfsApi({ + host: 'localhost', + port: 5001, + protocol: 'http', + headers: { + authorization: 'Bearer ' + TOKEN + } +}) +``` + ## Usage ### API diff --git a/src/utils/send-request.js b/src/utils/send-request.js index 90f436d47..eb9ea6adc 100644 --- a/src/utils/send-request.js +++ b/src/utils/send-request.js @@ -106,7 +106,7 @@ function requestAPI (config, options, callback) { delete options.qs.followSymlinks const method = 'POST' - const headers = {} + const headers = Object.assign({}, config.headers) if (isNode) { // Browsers do not allow you to modify the user agent diff --git a/test/custom-headers.spec.js b/test/custom-headers.spec.js new file mode 100644 index 000000000..2cf4c71c3 --- /dev/null +++ b/test/custom-headers.spec.js @@ -0,0 +1,61 @@ +/* eslint-env mocha */ +'use strict' + +const isNode = require('detect-node') +const chai = require('chai') +const dirtyChai = require('dirty-chai') +const expect = chai.expect +chai.use(dirtyChai) + +const IPFSApi = require('../src') +const f = require('./utils/factory') + +describe('custom headers', function () { + // do not test in browser + if (!isNode) { return } + this.timeout(50 * 1000) // slow CI + let ipfs + let ipfsd + // initialize ipfs with custom headers + before(done => { + f.spawn({ initOptions: { bits: 1024 } }, (err, _ipfsd) => { + expect(err).to.not.exist() + ipfsd = _ipfsd + ipfs = IPFSApi({ + host: 'localhost', + port: 6001, + protocol: 'http', + headers: { + authorization: 'Bearer ' + 'YOLO' + } + }) + done() + }) + }) + + it('are supported', done => { + // spin up a test http server to inspect the requests made by the library + const server = require('http').createServer((req, res) => { + req.on('data', () => {}) + req.on('end', () => { + res.writeHead(200) + res.end() + // ensure custom headers are present + expect(req.headers.authorization).to.equal('Bearer ' + 'YOLO') + server.close() + done() + }) + }) + + server.listen(6001, () => { + ipfs.id((err, res) => { + if (err) { + throw new Error('Unexpected error.') + } + // this call is used to test that headers are being sent. + }) + }) + }) + + after(done => ipfsd.stop(done)) +})