Objective: send {“username”: myuser, “password”: mypswd} to an API endpoint so I can obtain a token for further interaction with the API.
The code:
// Variation # 1 let res = await axios.post( url, { "username": args.username, "password": args.password }).then(res => { console.log(res) }) // Variation # 2 var params = new FormData() // required 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) }) // Variation # 2a var params = new FormData() // required 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) }) // Variation # 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 seem to pass the post data incorrectly. Using Wireshark, when I examine the request, the data passed is [object Object]
when I inspect the request packet.
If I run the same call to that API endpoint in PostMan and inspect the packet I see the following:
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
And of course, PostMan gives the expected token as the response.
Can anyone spot why the encoding fails for any/all of these variations? #1 is how the axios.post documentation suggests. The others are various suggested remedies I’ve found described on this site and elsewhere. This seems to have come up only as I’m trying to upgrade my code to Vue3. My Vue2 code was working with #2 (FormData).
Advertisement
Answer
There is no reason to use Axios. This should work:
const args = { "username": "someusername", "password": "somepassword" } const data = { "username": args.username, "password": args.password } const url = "https://google.com" fetch(url, { method: "POST", body: JSON.stringify(data) })