標題
- 實現邏輯:
登錄系統獲取cookie
判斷cookie是否有變化,有變化,更新cookie,沒有變化,使用舊的登錄cookie
開始進行發送報文或者文件上傳
2. 導入庫
const request = require('request')
const axios = require('axios')
const fs = require('fs')
// new FormData()
const FormData = require('form-data')
- 通過axios發送報文
// 定義全局的cookie,字符串
var globalCookie = ''
// 發送文件
async function sendByAxios(config){
await axios({
method: config.method,
url: config.url,
data: config.data,
headers: config.headers
})
.then(function(res){
cookie = res.headers['set-cookie']
response = res
// 全局爲空,有 全局爲空,沒有 全局非空,有 全局非空,沒有
if(!globalCookie && cookie){
for(var val in cookie){
globalCookie = globalCookie + cookie[val] + ';'
console.log('都爲空')
}
}
else if(globalCookie && cookie){
// 如果cookie不等於 'HttpOnly', 'Secure',更新cookie
// 需要更新的標誌
var updateFlag = false
for(var val in cookie){
if(cookie[val] != ['HttpOnly'] && cookie[val] != ['Secure']){
// 全部清除,還是連接字符串
if(updateFlag){
globalCookie = globalCookie + cookie[val] + ';'
console.log('都不爲空,且更新過')
}
else{
updateFlag = true
globalCookie = cookie[val]
console.log('都不爲空,沒有更新過')
}
}
}
}
else if(globalCookie && !cookie){
console.log('不需要更新')
}
else{
console.log('都沒有cookie')
}
});
// 處理res,返回data
const data = {};
data.status = response.status
data.data = response.data
data.headers = response.headers
data.req = response.config
data.cookie = globalCookie
return data
}
- 組裝報文併發送
async function runTest(){
// 定義返回的數據
let data ;
// 發送登錄
configLogin = {
method: 'POST',
url: 'https://xxx.cn/query',
data: {
"username": "xxx",
"password": "xxx@xxx"
},
headers: {
'ContentType': 'application/x-www-form-urlencoded',
'Cookie': globalCookie
}
}
// 返回數據
data = await sendByAxios(configLogin)
// 賦值cookie
globalCookie = data.cookie
console.log(data.data)
// 需要發送其他接口,需要闖入globalCookie
}
- 1
- 1
- 1
- 1
- 1