Alon
Alon

Reputation: 11935

Node.js request-promise jar cookies not working

I'm trying to make two API calls. The first one logs in, the last one performs an authorized operation. Even though the login succeeds, the call for the authorized operation produces a 401 unauthorized error. I think it's because the cookie I received isn't sent back in the last call. I've seen that the cookie is stored in jar though. I tried with Postman, and it worked well.

Here is my code:

const request = require('request-promise');

const jar = request.jar();

const loginOptions = () => ({
    method: 'POST',
    url: 'https://www.some-api.com/login',
    jar,
    headers:
    {
        'content-type': 'application/json'
    },
    body: {
        username: "username",
        password: "password"
    },
    json: true
});

const authorizedOperationOptions = (param) => ({
    method: 'GET',
    url: 'https://www.some-api.com/authorized-operation?param=' + param
    timeout: 1000000,
    jar,
    headers:
    {
        'content-type': 'application/json'
    },
    json: true
});

export default async (date) => {
    await request(loginOptions());
    await request(authorizedOperationOptions("value"));
};

I'd like to know what I'm doing wrong, but I'll also accept an alternative way to do so with a different library, with a working example code.

Notice that the service was designed to only support web browsers, so maybe it has something to do with that problem.

For those who are not familiar with await, it ensures code blocking until the promise is getting fulfilled, and throws in case of rejection.

Upvotes: 0

Views: 1998

Answers (1)

Alon
Alon

Reputation: 11935

Since the service is defined to only support web browsers, I had to impersonate a web browser. I managed it by adding a User-Agent header:

headers:
    {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6'
    },

Upvotes: 1

Related Questions