0

I need to add some parameters to this request:

fetch(url_ticket, {
    //body: JSON.stringify(data),
    //mode: 'no-cors',
    param: {
      'token': `${token}`,
      'id': `${id}`,
      'id_secret': `${id_secret}`
    },
    method: 'POST'
  })
  .then(response => {
      console.log(response.text());
    })
    .catch(error => {
    console.error(error);
    });

However, I'm getting an error. I've made that request in Postman an it works, so the problem is obviously in this code. I think the error is in the params parameter; how can I add properly parameters in this request?

I'm literally new to js, i've searched for answers but i can't understand a thing, so posting my real problem has been my last option

0

2 Answers 2

1

Here is the code to send post request with parameter

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

For info you can read doc here Using fetch

0

I think this SO answer is a nice and clean way to do it. Basically, it constructs the URL string with parameters.

fetch(url_ticket + new URLSearchParams({
    token: `${token}`,
    id: `${id}`,
    id_secret: `${id_secret}`
}), {});

You could also construct the parameters in a more manual way, by inserting the variables into a backticked URL string:

let url = `${url_ticket}?token=${token}&id=${id}&id_secret=${id_secret}`;

fetch(url, {...})

Not the answer you're looking for? Browse other questions tagged or ask your own question.