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

How to send requests using custom cookies with Request-promise

我正在开发打印应用程序,我需要从受保护的资源中获取一些数据。 我可以登录的唯一方法是使用浏览器,所以我使用 phantom 作为浏览器。 我设法登录并获取了 cookie,但我不知道如何使用带有请求承诺的 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 字符串 returns 解析为 object。它没有设置要在请求中发送的 cookie。

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

使用饼干罐

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);

使用 headers

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);