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

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

现在一个应用需要访问不同域下的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();

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


  还需注意以下两点:

  // 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);
【热门文章】
【热门文章】