error in post request using server-side buttons

Asked

Viewed 2,574 times

0

Good afternoon, I am creating a function in an api that will make a request via post, I did using fetch on the page with reactjs and now I have to migrate to the api but when making the request it generates an error saying that fetch is not a function, when migrating pro Xios and generated the following error:

(Ode:3612) Unhandledpromiserejectionwarning: Error: Request failed with status code 400

I know this error is given to the fact that the service is out of air but it was working with the fecth requisitions made on the page.

const dataCard = req.body;
let axiosConfig = {
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        MerchantId: "xxxxxxxxxxxxxxxxxxxx",
        MerchantKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    }
}
const url  = "https://apisandbox.braspag.com.br/v2/sales/"
const data = JSON.stringify(dataCard)


await axios.post(url,data,axiosConfig)
 .then((res)=>{
     console.log(res)
 })
  • My error was server-side and not client-side, the questions are different.

2 answers

0

I solved my problem this way:

const fetch = require("node-fetch");


fetch("https://apisandbox.braspag.com.br/v2/sales/", {
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        MerchantId: "xxxxxxxxxxxxxxxxxxxxx",
        MerchantKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    },
    body: JSON.stringify(dataCard),
})

0

The mistake UnhandledPromiseRejectionWarning is invoked by Node.js whenever a Promise is rejected and does not receive due treatment.


[...] I know this mistake is due to the fact that service being out of breath [...]

The fact that the service is off the air makes Axios unable to complete the request and therefore an error will be made. How the library in question works with Promises and you have not performed the proper treatment, the error will always be released when some problem happens during the request.

To treat the mistake directly in the promise chair, you can chain a catch. Something like that:

axios.post(url, data, config)
  .then((res) => {
    // Faça aqui o que quiser com a resposta da requisição.
  })
  .catch((error) => {
    // Trate o erro aqui.
    console.log('Whoops! Houve um erro.', error.message || error)
  })

If you are using async/await, can use the try/catch:

try {
  const response = await axios.post(url, data, config)
  // Faça aqui o que quiser com a resposta da requisição.
} catch (error) {
  // Trate o erro aqui.
  console.log('Whoops! Houve um erro.', error.message || error)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.