node 执行/运行 JavaScript / js脚本 测试axios /qs.stringify 对比JSON.stringify

demo1:

temp.js :

console.log('167464316')
//"C:\Program Files\nodejs\node.exe" C:\Users\able\Desktop\test\temp.js
// 如果node配置了环境变量且在当前目录下执行,可执行:
// node temp.js

执行 node temp.js

demo2:

let axios = require("axios");
//导入依赖需要用require,且末尾加分号
//"C:\Program Files\nodejs\node.exe" C:\Users\able\Desktop\test\temp2.js
// 如果配置环境变量且 当前文件夹下执行可以:
//  node temp2.js

(() => {
    const options = {
        method: 'POST',
        url: 'https://httpbin.org/post',
        headers: {'content-type': 'application/json'},
        data: {query: {a: 2, b: 1}}
    };

    axios.request(options).then(function (response) {
        console.log(response.data);
    }).catch(function (error) {
        console.error(error);
    });
})();

注意:第三方库需要安装,安装之后目录如下
在这里插入图片描述
package.json:

{
  "name": "test",
  "version": "1.0.0",
  "dependencies": {},
  "devDependencies": {
    "axios": "^0.21.0"
  }
}

qs.stringify 对比JSON.stringify

npm install qs
// let qs = require('qs');
import qs from 'qs';

let data = {
    "age": 18,
    "name": "xq"
};

//以&符号连接的字符串
console.log(`qs结果======${qs.stringify(data)}`)
//正常类型的json字符串
console.log(`JSON结果====${JSON.stringify(data)}`)
// qs结果======age=18&name=xq
// JSON结果===={"age":18,"name":"xq"}

测试axios的两种post:

let axios = require("axios");
let qs = require('qs')

function reqJson() {
    const options = {
        method: 'POST',
        url: 'https://httpbin.org/post',
        headers: {'content-type': 'application/json'},
        data: {query: {a: 2, b: 1}} //data : 自动转为json字符串
    };

    axios.request(options).then(function (response) {
        console.log(response.data);
    }).catch(function (error) {
        console.error(error);
    });
}

function reqUrlencoded() {
    let data = {
        "username": "ablexq1",
        "password": "xq123456"
    }
    const options = {
        method: 'POST',
        url: 'https://www.wanandroid.com/user/login',
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        data: qs.stringify(data), //data :以&符号连接的字符串
        timeout: 1000,//ms
    };

    axios.request(options).then(function (response) {
        console.log(response.data);
    }).catch(function (error) {
        console.error(error);
    });
}

(() => {
    reqJson()
    reqUrlencoded()
})();



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值