如何使用nodejs http API模拟web form表单提交?

发布于 2022-09-01 07:14:36 字数 1152 浏览 11 评论 0

现在一个应用需要访问不同域下的TAM安全认证服务,需要模拟form表单提交到WebSEAL,先谢谢了。以下是我目前尝试的http请求写法:

        var http = require('http');
        var querystring = require('querystring');

        var post_options = {
            host: '192.168.1.22',
            port: '80',
            path: '/pkmslogin.form',
            method: 'post',
            auth: 'username:123456',
            'login-form-type':'pwd',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
        var post_data = querystring.stringify({
            username:'username',
            password:'123456',
            'login-form-type':'pwd'
        });


        // Set up the request
        var post_req = http.request(post_options, function(res) {
            res.setEncoding('utf8');
            console.log(JSON.stringify(res.headers));

            res.on('data', function (chunk) {

                console.log('Response: ' + chunk);
            });
        });
        console.log(JSON.stringify(post_req.headers));


        // post the data
        //post_req.write(post_data);
        post_req.end();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ペ泪落弦音 2022-09-08 07:14:36
  还需注意以下两点:

  // 1、在头中设置好内容长度
   headers: {
    'Content-length': post_data.length,
    'Content-Type': 'application/x-www-form-urlencoded'
  }

  var post_data = querystring.stringify({
        username:'username',
        password:'123456',
        'login-form-type':'pwd'
    });
  // 2、参数写入到流中    
  post_req.write(post_data);
芯好空 2022-09-08 07:14:36

原生的api当然也可以,不过更推荐用github上7000+ stars的request

看介绍:

request supports application/x-www-form-urlencoded and multipart/form-data form uploads. For multipart/related refer to the multipart API.

Form 直达连接:https://github.com/request/request#forms

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文