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

劍唔风
  • 151

现在一个应用需要访问不同域下的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();
回复
阅读 12.7k
2 个回答
  还需注意以下两点:

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

原生的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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏