Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API.
The following code snippets attempt to achieve this:
// Attempt # 1
let res = await axios.post(
url, {
"username": args.username,
"password": args.password
}).then(res => { console.log(res) })
// Attempt # 2
var params = new FormData() // requires npm install form-data
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
url, params
}).then(res => { console.log(res) })
// Attempt # 2a
var params = new FormData() // requires npm install form-data
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
url, params, {
headers: {
'content-type': 'multipart/form-data'
}
}
}).then(res => { console.log(res) })
// Attempt # 3
var params = new URLSearchParams()
params.append("username", args.username)
params.append("password", args.password)
let res = await axios.post(
url, params
}).then(res => { console.log(res) })
All of the above approaches seem to be sending the post data incorrectly. When inspecting the request using Wireshark, the data seems to be [object Object]
.
If I make the same call to the API endpoint in Postman and analyze the packet, I see the following format:
Content-Type: multipart/form-data;
boundary=--------------------------074168144775996161656376
Content-Length: 293
----------------------------074168144775996161656376
Content-Disposition: form-data; name="username"
any.user.name
----------------------------074168144775996161656376
Content-Disposition: form-data; name="password"
MyPassword
Postman provides the expected token as the response in this case.
Is there anyone who can identify why the encoding is failing for these variations? The first approach (#1) follows the axios.post documentation, while the other methods are alternative solutions I have come across. This issue has surfaced as I am transitioning my code to Vue3 from Vue2 where I was successfully using Approach #2 (FormData).