node.js - 如何使用带有 Request-promise 的自定义 cookie 发送请求

标签 node.js request phantomjs

我正在开发一个打印应用程序,我需要从 protected 资源中获取一些数据。 我登录的唯一方法是使用浏览器,因此我使用 phantom 作为浏览器。 我成功登录并获取了 cookie,但我不知道如何使用具有 request-promise 的 cookie 来使用我登录时获得的 cookie 发送请求。

这是我的简化代码:

import * as phantom from "phantom";
import * as requestPromise from "request-promise-native";
requestPromise.defaults({ rejectUnauthorized: false });

(async function () {
    const instance = await phantom.create([
        "--ignore-ssl-errors=true",
        "--cookies-file=cookies.txt",
        "--web-security=false",
        "--ssl-protocol=any"
    ]);
    const page = await instance.createPage();
    const status = await page.open("http://localhost:3000/auth/login-html");
    console.log("status", status);

    let result = await page.evaluate(() => {
        (document.getElementById("username") as HTMLInputElement).value = "test@email.com";
        (document.getElementById("password") as HTMLInputElement).value="password";
        (document.getElementById("login") as HTMLElement).click();

        return true;
    });
    // Get the cookies 

    let cookies = await page.property("cookies");
    console.log(cookies)
    /** [{ domain: 'my-app-resource-domain.com',
        httponly: true,
        name: 'ticket',
        path: '/',
        secure: false,
        value: '6823a-78c0a4ee82c0' },
        { domain: 'my-app-resource-domain.com',
        httponly: true,
        name: 'JSESSIONID',
        path: '/',
        secure: false,
        value: '9CB8396A05ABA178' }] **/
    let cookiesSring = getStringCookies(cookies) // "ticket=6823a-78c0a4ee82c0&JSESSIONID=9CB8396A05ABA178"
    requestPromise.cookie(cookiesSring );

    // Send request to get data from protected resource 
    let res = await requestPromise.get("http://my-app-resource-domain.com/api/get-charts")
})();

最佳答案

文档对此非常不清楚,但是 cookie 函数实际上只是解析并返回 cookie 字符串作为对象。它不会设置要在请求中发送的 cookie。

你有两个选择。您可以使用 tough-cookie 创建 cookie jar 并将其包含在选项中,如 shown in the official documentation ,或者您只需将 Cookie 直接包含在 header 中即可。

使用 cookie jar

import * as requestPromise from "request-promise-native";
import { Cookie } from "tough-cookie";

// ...

const pageCookies = await page.property("cookies");
// rename the "httponly" property to "httpOnly" since that's what
// tough-cookie expects
const cookies = pageCookies.map(pageCookie => {
    const cookie = { ...pageCookie };
    cookie.httpOnly = pageCookie.httponly;
    delete cookie.httpOnly;
    return new Cookie(cookie);
});

const cookieJar = requestPromise.jar();
// Set the cookies to apply only to my-app-resource-domain.com
cookies.forEach(cookie =>
    cookieJar.setCookie(cookie, "http://my-app-resource-domain.com/")
);

const options = {
    uri: "http://my-app-resource-domain.com/api/get-charts",
    jar: cookieJar
};

const res = await requestPromise.get(options);

使用 header

import * as requestPromise from "request-promise-native";
import * as querystring from "querystring";

// ...

const pageCookies = await page.property("cookies");

// pluck the name and value from the page cookies into
// key-value pairs in an object
const cookieObjects = pageCookies.reduce((acc, cookie) => {
    acc[cookie.name] = cookie.value;
    return acc;
}, {});

// stringify the cookies to the familiar "cookie=value; cookie2=value" format
const cookieString = querystring.stringify(cookieObjects, "; ");

const options = {
    uri: "http://my-app-resource-domain.com/api/get-charts",
    headers: {
        Cookie: `${cookieString};`
    }
};

const res = await requestPromise.get(options);

关于node.js - 如何使用带有 Request-promise 的自定义 cookie 发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910315/

相关文章:

ruby-on-rails - 无法使用 Poltergeist 和 PhantomJS 测试 Angular UI Typeahead

java - 使用套接字的 Http 请求

tomcat - 如何拦截tomcat上的传出请求?

windows - node.js 无法识别 express

node.js - 为 session 设置服务器端 cookie 的正确方法

python - "An Existing Connection was Forcibly Closed by the Remote Host"为什么?我该如何解决?

selenium - Phantomjs session 隔离仍然不起作用吗?

angularjs - 'undefined' 不是一个函数(评估'_.contains)业力测试

node.js - Node : PORT 443 requires elevated privileges error

Node.js 表示,当 minVersion 设置为 1.3 时,它正在使用 tls1.2 并使用 1.3 与客户端连接