![](/img/trans.png)
[英]fetch-api in express app with body parser has blank request body if using form object
[英]post request successful with Postman - unsucessful with fetch-api
由於以下問題,過去兩天我一直在用頭撞牆。
這是場景:當我通過瀏覽到特定網站發出 GET 請求時,該網站發送一個名為 PHPSESSION="xyz" 的 cookie,然后提示用戶輸入密碼,隨后向同一個 URL 發出發送請求特定的 cookie 和隱藏的表單元素一起用於驗證,成功后發送 pdf。
我可以在 Postman 中成功復制它。
我發出一個獲取請求 - 它設置了 cookie - 我在我的表單數據響應正文中填寫了密碼,並手動添加了添加到表單以進行驗證的秘密字符串 -> 發送...我得到了 pdf - 到目前為止超好的。
但是,我想使這個過程自動化,這樣我就不必費力地手動提取隱藏表單的值,而是使用 node.js 來發出這些請求,所以我編寫了以下代碼:
// making the get request to the URL above
// extract the cookie PHPSESSION value
const sessionString = String(response.headers.get('set-cookie')).substring(10,36)
// parse the body
const htmlBody = await response.text()
let doc = new DOMParser().parseFromString(htmlBody)
// extract the verification token from the form
const formToken = await doc.getElementById('verification__token').getAttribute('value')
let formData = new FormData();
formData.append('verification[char_1]',0)
formData.append('verification[char_2]',6)
formData.append('verification[char_3]',4)
formData.append('verification[char_4]',5)
formData.append('verification[char_5]',8)
formData.append('verification[char_6]',1)
formData.append('verification[char_7]',7)
formData.append('verification[char_8]',6)
formData.append('verification[_token]',formToken)
const obj = {
headers:{
"Cookie" : `PHPSESSID=${sessionString};`,
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "PostmanRuntime/7.29.2",
"Accept-Encoding": "gzip, deflate, br",
"credentials": "include"
},
method: "POST",
body: formData
}
const postResponse = await fetch("https://url...",obj)
const r = await postResponse.text()
不幸的是,發布請求在 node.js 中失敗了——該網站只是將我重定向到我必須輸入密碼的表單。
我懷疑它與標頭/cookie 有關,但我根本不知道。 有沒有人發現一個明顯的錯誤?
謝謝
解決了......在犧牲了整個周末來完成這項可愛的任務之后。 如果有人遇到類似的問題,這里就是解決方案 - 或者至少對我有幫助。
https://reqbin.com/curl https://curlconverter.com
所以基本上讓你的請求與 curl 一起工作,然后移植它。 就我而言,它看起來像這樣:
const x = await fetch('https://yourURL', {
method: 'POST',
headers: {
'Cookie': 'PHPSESSID=lfjdd2uba1bmecr064rt7chvu3; Path=/; Secure; HttpOnly;',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'verification[_token]=5d5e4d8783daf952d5.UZ661yMyOUtJSQeG1Td7cUtxWqnI2Oaot-xMQevly4o.acH9hXR9SRkwGm30kE9WIggDNpqdl6Ln2rQnOIG9pcEp1tOiYnNLJggZcA&verification[char_1]=0&verification[char_2]=6&verification[char_3]=4&verification[char_4]=5&verification[char_5]=8&verification[char_6]=1&verification[char_7]=7&verification[char_8]=6'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.