node 執行JavaScript 指令碼 測試axios

Mars-xq發表於2020-12-19

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"
  }
}

測試axios的兩種post:

let axios = require("axios");

function reqJson() {
    const options = {
        method: 'POST',
        url: 'https://xxx.xxxxx.xxxx/v1/auth/login',
        headers: {'content-type': 'application/json'},
        data: { //這裡是data 
            "email": "776356314@qq.com",
            "password": "xq123456"
        }
    };

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

function reqUrlencoded() {
    const options = {
        method: 'POST',
        url: 'https://www.wanandroid.com/user/login',
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        params: { //這裡是params
            "username": "ablexq1",
            "password": "xq123456"
        }
    };

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

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

相關文章