首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用带有Request-promise的自定义cookie发送请求

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

Stack Overflow用户
提问于 2018-08-18 23:55:18
回答 1查看 2.6K关注 0票数 1

我正在开发一个打印应用程序,我需要从受保护的资源中获取一些数据。我登录的唯一方式是使用浏览器,所以我使用phantom作为浏览器。我设法登录并获得cookie,但我不知道如何使用cookies与请求-承诺与我登录时获得的cookie一起发送请求。

以下是我的简化代码:

代码语言:javascript
复制
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")
})();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-19 01:38:01

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

您有两个选择。您可以使用tough-cookie创建cookie jar并将其作为shown in the official documentation包含在选项中,也可以直接将cookie包含在标头中。

使用cookie jar

代码语言:javascript
复制
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);

使用标头

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51910315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档