-
Notifications
You must be signed in to change notification settings - Fork 762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Set Authorization header to post request #398
Comments
You do want to use the
In your first example I would say that there is a problem with the variable |
this does not work. |
Note that you have to call request(app)
.set('Authorization', 'abc123') // DOES NOT WORK
.post('/api')
request(app)
.post('/api')
.set('Authorization', 'abc123') // Works. |
It's TERRIBLE !!! |
Well it would only make sense to do that since in a real-life scenario you are making separate HTTP Requests, each having its own separate Header. Unless I understood you wrong? |
@christopheelkhoury In a real-life app, i would set auth header in state and create a new instance of HttpRequest which hold the auth header. For example this is my HttpService:
And i'll call it like:
So there is no duplication of code and i can change header or auth method easily by changing one line of code. But the syntax in super test makes me to set header separately for each request which is not clean and not DRY |
@JafarAkhondali If you are talking about setting up the header for multiple routes then you can do something like make function which will execute before all the test case and freom there get that header value and set it in others routes so in that way you dont have to write the same request code all the time whereas only thing you have to do is to set the value using Example: -
now use that |
Separe the const URL = `My Endpoint`;
const TOKEN = 'Secret';
const hook = (method = 'post') => (args) =>
supertest(URL)
[method](args)
.set('Authorization', `Basic ${TOKEN}`);
const request = {
post: hook('post'),
get: hook('get'),
put: hook('put'),
delete: hook('delete'),
};
export default request; I dont touch my tests code |
I'm trying to set header but is not part of the headers
This is the headers object:
Any idea how to append Authorization to the headers? I also tried .set(Authorization, 'abc123') |
@AndonMitev I'm guessing you're using the request package.
|
// if you setup ur server to response with a token after a login operation u can authorize the get/post individual operation as follow .N.B // token = a string sent back as response header to the browser by a server
|
Sometimes - eg while running integration tests - it completely makes sense to set same headers for all requests. |
It is possible by using the agent it self, and calling Calling import { agent as supertest } from 'supertest';
// ---------^ this is the important part, using the agent itself.
import app from './app';
agent = supertest(app);
const response = await agent.post('/api/auth/login', { username: 'tester', password: 'tester' });
agent.auth(response.accessToken, { type: 'bearer' });
// this request will include the Authorization header
agent.post('/api/customer/add', { name: 'foo' }); |
Peace, @vegaByte @felixmosh @thelebdev I have an internal server error with the following. Anyone knows why? Here is the repo https://github.com/camariana/fs-blog-list `
}) |
@vegaByte, How do you go about implementing this? |
Can anyone help here? |
Why not using const defaultAgent = new Proxy(supertest(app), {
get: (target, name) => (…args) =>
(target as any)[name](…args).set({
'Authorization': `Bearer ${defaultToken}`,
'Accept': 'application/json',
}),
}) Then you can use just as any agent: defaultAgent.get('url')
defaultAgent.post('url')
... You can set any properties in the proxy. |
I have resolved with a simple monkey patching // ...
beforeAll(() => {
request = supertest(app.getHttpServer());
// Next line is important or recursion hell will kill your code
const originalMethod = request.patch;
request.patch = (url: string, ...args) => {
return originalMethod(url, ...args)
.set('Content-Type', 'application/json')
.set('X_CONNECTION_KEY', 'XXX');
};
});
// ... |
I noticed a strange behavior today with a delete request: This works: request(app)
.delete(`/resource/${id}`)
.set({ Authorization: `Bearer ${token}` })
.expect(204); // Passes But this does not work: const response = await request(app)
.delete(`/resource/${id}`)
.set({ Authorization: `Bearer ${token}` });
expect(response.statusCode).toBe(204); // Fails --> 401 What is the problem here? |
calling delete before the set will execute the request before you set the header. |
Thanks for your reply. The example in the README uses the GET verb, but the call is very similar: describe('GET /users', function() {
it('responds with json', async function() {
const response = await request(app)
.get('/users')
.set('Accept', 'application/json')
expect(response.headers["Content-Type"]).toMatch(/json/);
expect(response.status).toEqual(200);
expect(response.body.email).toEqual('foo@bar.com');
});
}); |
how can i set authorization for API KEY ? |
Hopefully this can help you, @techrook ` const request = supertest(REQRES_BASE_URI) export const makeGETCall = async (endpoint: endpoints | string) => { |
.env file TOKEN = 'averylongstring' case 1: await api.post('/').set('Authorization ' ,'Bearer ${process.env.TOKEN') // this fails with 400 status code case 2: const token = 'averylongstring'
await api.post('/').set('Authorization ' ,'Bearer ${token') // this pass why is this happening |
Because in case 1 you have wrong syntax. You are missing backtics `` and one bracket await api.post('/').set('Authorization ' ,`Bearer ${process.env.TOKEN}`) |
.set("Authorization", |
Whoever come to this issue, there's a simpler way of doing this, using the underlying Instead of this (unfortunately it doesn't work) request(app)
.set('Authorization', 'abc123')
.post('/api'); You can do request.agent(app)
.set('Authorization', 'abc123') // Using the superagent behind supertest
.post('/api'); You can do even better if you export the server and reuse it across tests: export const server = request.agent(app).set('Authorization', 'abc123');
//[...]
server.post('/api').expect(201);
server.get('/other-api').expect(200); |
Why is this closed ?.? |
Error:
Error: "value" required in setHeader("Authorization", value)
Error:
TypeError: (0 , _supertest2.default)(...).post(...).send(...).setHeader is not a function
How set header to post request ?
The text was updated successfully, but these errors were encountered: