简体   繁体   中英

Node.js: Axios vs Fetch using x-www-form-urlencoded

I normally use Axios for my API requests, but I'm having an issue hitting an external API with Axios for some reason.

Fetch on the other hand works fine with this particular request.

I'm trying to figure out what I'm doing wrong here.

Axios:

 async function getToken(req, res) { const apiCreds = { 'grant_type': 'client_credentials', 'client_id': xxxxxxxxxxxx, 'client_secret': xxxxxxxxxxxx, 'scope': 'PublicAPI' } const header = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } const token = await axios.post(`${process.env.URL}`,qs.stringify(apiCreds),header) res.status(200).json({'TokenData': token}) }

I tried adding qs.stringify to the object body, but that didn't work either.

Fetch:

 async function getToken(req, res) { const apiCreds = { 'grant_type': 'client_credentials', 'client_id': xxxxxxxxxxx, 'client_secret': xxxxxxxxxxxxx, 'scope': 'PublicAPI' } fetch(`${process.env.VS_URL}`, { method: 'post', body: qs.stringify(apiCreds), headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, }).then(res => res.json()).then(json => { res.status(200).json({'TokenData': json}) }); }

I really want to know what I'm doing wrong here so I can stick with one package if possible.

Any feedback is appreciated!

This was completely my fault. I didn't realize the API call actually went through and I was getting a JSON circular error! I just needed to format the data from the result of the API call.

res.status(200).json({'TokenData': token.data.access_token})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM