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()
})();