1

Goal:
Use Axios to send a post from client to backend

Problem:
Axios code cannot send data to the backend while fetch code can make it.

The data, in relation, to axios will be id = 0 and firstname = null at backend

It works well when I use fetch code and I can see it at backend

Main difference is the "Request Header > Accept" (take a look at the picture).

How should I enable to make it to "/" instead of Application/json, text/plain, / at "Request Header > Accept"?

Thank you!


const params = { 
  id: 1,
  firstName: "sdf"
}

var config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  accept: { }
};

axios.post('http://localhost:1122/api/v1/Test/AddClient', params, config)
.then(response => {
})
.catch(error => {
  console.log(error.response)}
);
 

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var urlencoded = new URLSearchParams();
urlencoded.append("id", "1");
urlencoded.append("firstName", "sdf");

let requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded
};

fetch("http://localhost:1122/api/v1/Test/AddClient", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

enter image description here

enter image description here

HelloWorld1
  • 13,688
  • 28
  • 82
  • 145
  • I'd suggest adding the `params` object to `config` as a property named `data`. And change `Content-Type` value to `application/json` – arturasmckwcz Jan 22 '22 at 12:11
  • It doesn't work to use 'application/json' in this context. I haved used application/json before but not this time. – HelloWorld1 Jan 22 '22 at 19:31

1 Answers1

1

Accept is a header to change the value of accept to "/" you need to add it to the request headers You created the config object correctly but accept should be in headers

var config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'accept': '*/*',
  },
};