I can not find in the documentation how to set headers for the request.
How can I bypass this check in supertest?
router.use (req, res, next) ->
return next() if req.headers.authorization is 'somekey'
res.send 401
You just set them when you create the request.
request(server)
.post('/some-path')
.auth('user', 'password')
.end(callback)
Thanks @gjohnson. I was wondering how to do this as well
Since this came up in my searches when I was trying to find the answer to this question I'll post what I found to be the answer if you are using a token rather than username & password:
request(app)
.get('/path')
.set('Authorization', 'Token token=blahblahblah')
.end(callback)
This works better is you are trying to set tokens with crypto.createHmac or something along the lines of the AWS Signing and Authenticating Rest Requests.
If you are using tokens in your app to frontend consider using JWT - but I guess that is getting off topic.
I am unable to set a custom header
I have token middleware that will verify a jwt token in the 'x-access-token' header. but doing something like this
request(app)
.put('/user/' + a_user_id)
.set('x-access-token', myToken)
.end(callback);
The 'x-access-token' header is never set
any workaround on this?
Also looking for a work around to the same problem as @schmittyjd
@charliedavison I just had the same issue as @schmittyjd and I found out it was because the value for the header (in his case myToken) was null ... duh!
Hope it helps you save some time!
Still does not work with supertest 2.3.0
Setting headers with supertest works perfectly but I noticed it sets them lowercased, so the problem could be that you are checking for req.headers['Authorization'] and of course it doesn't find the key.
A little workaround to get the proper header key:
const getToken = (authorizationHeader) => authorizationHeader.replace(/^Bearer /i, '');
// Note: according to RFC 2616 and 7230 headers are case insensitive, so we need to check both or get the proper one
const key = Object.keys(req.headers).filter(k => k.toLowerCase() === 'authorization')[0];
const jsonWebToken = (key && req.headers[key]) ? getToken(req.headers[key]) : '';
If you still in doubt just log to the console what you receive on req.headers when using supertest.
Checked this with supertest v2.3.0 and v3.0.0.
If you still find the bug, please provide a minimal set up to reproduce it.
Is there any plan to prevent the automatic lowercasing?
Most helpful comment
I am unable to set a custom header
I have token middleware that will verify a jwt token in the 'x-access-token' header. but doing something like this
The 'x-access-token' header is never set