新手请教一个问题:关于Nodejs的学习路径

新手请教一个问题:关于Nodejs的学习路径

有这样一个需求,就是模拟浏览器登录。 需要这样做:

  • 先get一次某url :LOGIN_URL拿到必须的参数
  • 接着post这个LOGIN_URL,把上一步get到的数据重新组织POST过去

我用的是needle

这样

needle.get(LOGIN_URL, function(err, resp, body){
    //process parameters
    needle.post(LOGIN_URL, function(err, resp, body){
        //到这里就会卡住,post不出去,
    })
})

请问该怎么解决?


8 回复

当然可以!根据你的需求,使用 Node.js 来模拟浏览器登录涉及两个主要步骤:首先通过 GET 请求获取必要的参数,然后使用这些参数进行 POST 请求。你提到在使用 needle 库时遇到了问题,导致 POST 请求无法成功发送。

下面是一个完整的示例代码,展示如何正确地完成这个任务。我们将使用 needle 库来处理 HTTP 请求,并确保所有的参数都被正确传递。

首先,你需要安装 needle 库:

npm install needle

然后,你可以使用以下代码来实现你的需求:

const needle = require('needle');

// 定义 URL 和其他参数
const LOGIN_URL = 'https://example.com/login';
const loginData = {
    username: 'your_username',
    password: 'your_password'
};

// 第一步:GET 请求以获取必要的参数
needle.get(LOGIN_URL, { follow_max: 10 }, (err, resp, body) => {
    if (err) {
        console.error('GET request failed:', err);
        return;
    }

    // 解析响应体以获取必要的参数(假设服务器返回 JSON)
    const responseParams = JSON.parse(body);

    // 第二步:POST 请求
    const postOptions = {
        form: {
            ...loginData,
            ...responseParams
        },
        follow_max: 10
    };

    needle.post(LOGIN_URL, postOptions, (err, resp, body) => {
        if (err) {
            console.error('POST request failed:', err);
            return;
        }

        console.log('Login successful:', body);
    });
});

代码解析

  1. 引入 needle 库

    const needle = require('needle');
    
  2. 定义 URL 和登录数据

    const LOGIN_URL = 'https://example.com/login';
    const loginData = {
        username: 'your_username',
        password: 'your_password'
    };
    
  3. 第一步:GET 请求

    • 使用 needle.get 发送 GET 请求。
    • 在回调函数中,检查是否有错误并处理响应体(假设响应体为 JSON)。
    needle.get(LOGIN_URL, { follow_max: 10 }, (err, resp, body) => {
        if (err) {
            console.error('GET request failed:', err);
            return;
        }
        const responseParams = JSON.parse(body);
    });
    
  4. 第二步:POST 请求

    • 将从 GET 响应中获取的参数与登录数据合并。
    • 使用 needle.post 发送 POST 请求。
    • 在回调函数中,检查是否有错误并处理响应体。
    const postOptions = {
        form: {
            ...loginData,
            ...responseParams
        },
        follow_max: 10
    };
    
    needle.post(LOGIN_URL, postOptions, (err, resp, body) => {
        if (err) {
            console.error('POST request failed:', err);
            return;
        }
    
        console.log('Login successful:', body);
    });
    

这个示例展示了如何使用 needle 库来完成你的需求。确保替换 LOGIN_URLusernamepassword 为你实际使用的值。希望这能帮助你解决问题!


POST 不出去? 是报错了还是回调函数没有执行?

推荐用request : https://github.com/mikeal/request 个人觉得needle不太好用

回调执行了,post那一块卡住了,因为超时

谢谢,试一下

request的cookie你成功过没,无论怎么样cookiejar都是空的

sorry,因为本来cookie就是空的。。。

要实现通过 Node.js 模拟浏览器登录的需求,可以使用 needle 库来处理 HTTP GET 和 POST 请求。你的问题在于如何正确地处理异步操作,确保在完成 GET 请求后才进行 POST 请求。

下面是一个完整的示例代码,展示了如何使用 needle 完成这个任务:

const needle = require('needle');

const LOGIN_URL = 'https://example.com/login';
const LOGIN_DATA = {
    username: 'yourUsername',
    password: 'yourPassword'
};

// Step 1: Get initial parameters (if any)
needle.get(LOGIN_URL, (err, resp, body) => {
    if (err) {
        console.error('Error during GET request:', err);
        return;
    }

    // Assuming the login form has some CSRF token or other hidden fields
    const csrfToken = parseCsrfToken(body);  // Implement this function to extract the token from the response

    // Step 2: Post the login data with the CSRF token
    const postData = {
        ...LOGIN_DATA,
        _csrf: csrfToken
    };

    needle.post(LOGIN_URL, postData, (err, resp, body) => {
        if (err) {
            console.error('Error during POST request:', err);
            return;
        }

        console.log('Login successful:', body);
    });
});

function parseCsrfToken(html) {
    // This is a placeholder function. You should implement logic to parse the CSRF token from the HTML.
    // For example, you might use a library like `cheerio` to parse the HTML.
    return 'example_csrf_token';  // Replace with actual parsing logic
}

解释:

  1. 导入 needle:首先导入 needle 库来处理 HTTP 请求。
  2. 定义常量:定义登录 URL 和初始的登录数据。
  3. GET 请求:发送 GET 请求以获取必要的参数(例如 CSRF token)。
  4. 处理响应:从响应中提取 CSRF token。
  5. POST 请求:使用提取到的 CSRF token 更新登录数据,并发送 POST 请求。
  6. 错误处理:添加错误处理逻辑,确保在网络请求失败时能够捕获并处理错误。

注意事项:

  • 实际项目中,可能需要解析复杂的 HTML 来获取 CSRF token,这里使用了一个简单的 parseCsrfToken 函数作为示例。
  • 确保你已安装 needle 库:可以通过运行 npm install needle 来安装。

这个示例展示了如何使用 needle 库来完成一个典型的登录流程,希望对你有所帮助!

回到顶部