简体   繁体   English

Node.js请求承诺jar cookie无法正常工作

[英]Node.js request-promise jar cookies not working

I'm trying to make two API calls. 我正在尝试进行两个API调用。 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. 即使登录成功,对授权操作的调用也会产生401未经授权的错误。 I think it's because the cookie I received isn't sent back in the last call. 我认为这是因为我收到的Cookie没有在上次通话中发回。 I've seen that the cookie is stored in jar though. 我已经看到了该cookie 保存jar虽然。 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. 请注意,该服务旨在仅支持Web浏览器,因此也许与该问题有关。

For those who are not familiar with await , it ensures code blocking until the promise is getting fulfilled, and throws in case of rejection. 对于不熟悉await ,它可以确保代码阻塞直到实现诺言为止,并在拒绝时抛出。

Since the service is defined to only support web browsers, I had to impersonate a web browser. 由于该服务被定义为仅支持Web浏览器,因此我不得不模拟一个Web浏览器。 I managed it by adding a User-Agent header: 我通过添加User-Agent标头来管理它:

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'
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM