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

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

1 Answer 1

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': '*/*',
  },
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.