zoukankan      html  css  js  c++  java
  • nodejs querystring踩坑笔记----只能用于表单提交

    API中的实例:

    var http = require('http');
    var querystring = require('querystring');
    var postData = querystring.stringify({
      'msg' : 'Hello World!'
    });
    
    var options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };
    
    var req = http.request(options, (res) => {
      console.log(`STATUS: ${res.statusCode}`);
      console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
      });
      res.on('end', () => {
        console.log('No more data in response.')
      })
    });
    
    req.on('error', (e) => {
      console.log(`problem with request: ${e.message}`);
    });
    
    // write data to request body
    req.write(postData);
    req.end();

    刚开始不理解querystring是干什么的,本想这里不用JSON.stringify()应该是Node特有的方法吧,也没打印出来看。

    当我将一个obj对象(含多层)POST发送给服务器时,一直不对。

    这里已经改为:

    'Content-Type': 'application/json'

    还是不对。

    最后

    var querystring = require('querystring');
    
    var postData = querystring.stringify({
        name:'abc',
        age: 12,
        array:[{name:'234'},{name:'987'}]
    })
    
    console.log(postData);

    明显:对于多级obj经由querystring处理之后就不对了。

    很快就明白了,原来querystring是将对象转为表单格式的字符串,so querystring只能用于application/x-www-form-urlencoded的情况。

    form请求是没办法处理层级问题的。

    对于application/json还是用JSON.stringify()吧。

    对于node请求建议还是使用npm第三方封装的请求工具 如:request 或者javascript原生的fetch

     
  • 相关阅读:
    Oracle 备份脚本
    Centos 安装DBI和ORACLE DBD
    人生到此初相见——北漂18年(10)
    备份上个月的日志
    mysql 授权
    竹杖芒鞋轻胜马,一蓑烟雨任平生——写在38岁生日
    haproxy 跨域访问:
    redis 配置说明
    vsftpd 500 OOPS: bad bool value in config file for: anon_world_readable_only
    vsftpd 配置虚拟用户
  • 原文地址:https://www.cnblogs.com/jay763190097/p/6742220.html
Copyright © 2011-2022 走看看