Nodejs怎么模拟登陆?

Nodejs怎么模拟登陆?

var http = require(“http”); var querystring = require(“querystring”);

var options = { hostname: ‘127.0.0.1’, port: 9000, path: ‘/modules/login/checkSign.php’, method: ‘POST’ }; var contents = querystring.stringify({ username: ‘admin’, password: ‘123456’ }); var req = http.request(options, function(res) { res.setEncoding(‘utf8’); res.on(‘data’, function (data) { console.log(‘BODY:’ + data); }); });

req.on(‘error’, function(e) { console.log('problem with request: ’ + e.message); });

req.write(contents); req.end(); 接收不到这里提交的参数呢?请各路大神指教一下!


4 回复

当然可以。你提供的代码尝试使用 http 模块来模拟登录请求,但存在一些问题。首先,你需要使用 https 模块而不是 http 模块,因为很多网站使用 HTTPS 协议。其次,你需要确保服务器端能够正确解析 POST 请求中的数据。

以下是一个改进后的示例代码,使用了 https 模块,并且使用了 https 模块的 request 方法来发送 POST 请求。此外,我们还会使用 tls 模块来处理 SSL/TLS 加密连接。

const https = require('https');
const querystring = require('querystring');

// 设置请求选项
const options = {
    hostname: '127.0.0.1',
    port: 9000,
    path: '/modules/login/checkSign.php',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(contents)
    }
};

// 构造表单数据
const contents = querystring.stringify({
    username: 'admin',
    password: '123456'
});

// 创建请求对象
const req = https.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Response received:', data);
    });
});

req.on('error', (e) => {
    console.error(`Problem with request: ${e.message}`);
});

// 发送表单数据
req.write(contents);

// 结束请求
req.end();

解释

  1. 使用 https 模块

    • 大多数现代网站使用 HTTPS 协议,因此我们需要使用 https 模块而不是 http 模块。
  2. 设置请求头

    • 我们需要设置 Content-Typeapplication/x-www-form-urlencoded,这是 HTML 表单默认的编码类型。
    • Content-Length 是请求体的长度,这里我们使用 Buffer.byteLength 来计算长度。
  3. 处理响应

    • 我们监听 data 事件来收集响应数据,并在 end 事件中打印出完整的响应。
  4. 错误处理

    • 我们监听 error 事件来捕获任何可能发生的错误。

通过这些修改,你的 Node.js 应用应该能够成功地向服务器发送 POST 请求并接收响应。


supertest npm or postman

options no headers

你的问题在于使用了http模块,而不是更适合处理HTTP请求的httpsaxios库。此外,你应该确保后端服务能够正确解析POST请求中的数据。

以下是一个使用axios库来模拟登录的例子。axios库更为现代且功能强大,可以更方便地处理HTTP请求:

const axios = require("axios");

async function login() {
    const response = await axios.post("http://127.0.0.1:9000/modules/login/checkSign.php", {
        username: "admin",
        password: "123456"
    });

    console.log(response.data);
}

login().catch(console.error);

在这个例子中,我们使用了axios.post方法来发送POST请求,并直接传入需要提交的数据。这样可以避免手动使用querystring.stringify和设置请求体的问题。

另外,请确保后端服务能够正确解析POST请求中的数据。如果你的服务端是PHP,可能需要使用$_POST变量来获取数据,而不是通过GET或其他方式。

总结:

  1. 使用axios库替代http模块。
  2. 确保后端能正确解析POST请求中的数据。
回到顶部