axios doesn't send post data to the back-end - reactjs

I'm new to react and.my problem is that i'm going to make a post request to my node back-end. using react-redux and axios. the thing is my back-end doesn't even hit the request. and no action on the network tab in the browser ether
I have tried lots of another answers but doesn't work
this code is in my redux action page
export const postNominationPayments = function
postNominationPayments(candidatePayments) {
let nominationPayments = {
depositor:candidatePayments.depositor,
depositAmount:candidatePayments.depositAmount,
depositeDate:candidatePayments.depositeDate,
filePath:candidatePayments.filePath,
status:candidatePayments.status,
nominationId:candidatePayments.nominationId
};
return function (dispatch) {
console.log("**",nominationPayments);
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
axios
.post(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
.then(response => {
console.log("))))))))))))",response);
// dispatch({
// type: POST_NOMINATION_PAYMENTS,
// payload: response.data
// })
})
.catch(error => {
console.log("===",error);
// dispatch({ type: AUTH_FAILED });
// dispatch({ type: ERROR, payload: error.data.error.message });
});
};
}
post data is coming as expected.also the back works correctly using postman. but it's not working.
couldn't think of a solution.
what is wrong with my code?
thanks in advance

It should be
axios.post(
`${API_BASE_URL}/nominations/payments`, nominationPayments,
{headers: headers}).
One can drop headers section as well a default is application/json

The way you are passing data to axios post request is incorrect. You need to pass something like below
Change
axios(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
To
axios.post(
`${API_BASE_URL}/nominations/payments`,
nominationPayments,
{
headers: headers
}
)

axios.get and axios.post takes different kind of arguments and could be hard to remember.
So I usually just stick to the more verbose way:
axios({
method: 'post',
url: `${API_BASE_URL}/nominations/payments`,
data: {
nominationPayments
},
headers
})
.then(response => {
// ...
})
.catch(error => {
// ...
})

Have you checked whether your MongoDB server is up and running?
In my case, my React server was running, however, my MongoDB servers were not. I ran both simultaneously and was able to post data to the back end.

Related

How to send body data and headers with axios get request?

I've tried
axios.get(url, {headers:{},data:{}})
But it doesn't work with this.
You should refer to https://github.com/axios/axios#request-config
Check the section for data and header.
As far as I know you can't send body data with GET request. With get you can have only Headers. Just simply change to POST and then you can do something like this :
const bodyParameters = {
key: "value",
};
const config = {
headers: { Authorization: `Bearer ${userToken}` },
};
axios.post("http://localhost:5000/user", bodyParameters, config)
.then((res)=> {
console.log(res)
})
.catch((err) => console.log(err));
};
or if you want to send headers with GET request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
https://stackoverflow.com/a/54008789
yeah, it's true it doesn't work to send body in Axios get even if it works in the postman or the backend.
You can try this:
const getData = async () => {
try {
const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
method: 'POST',
body: JSON.stringify({
id: id,
title: 'title is here',
body: 'body is here',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
}
You can send data in a get request by using the config object and the params option of the config object. This is a workaround and it works, but on the server the data sent is available as request.query not as request.body. Based on the example below you would access your params data on your server using request.query.user_id. It should be noted that using this method will also append the params to your request url which could have unintended consequences based on your specific situation. For example, the url for the request below would be sent as example.com?user_id=1234. You can read more about the axios request config here.
axios.get(
'example.com/',
{
params: { user_id: 1234 },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
);

Body of request received on Express backend is different than how i sent it from React frontend

I am trying to send a post request from my React front end to my Express front end, for some reason, the object I want to recieve, is being displayed so that the object is the key of another object and the value is and empty string.
Here is my onSubmit React function
handleSubmit = event => {
event.preventDefault()
const backend = '/api/login'
fetch(backend, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: JSON.stringify(this.state)
})
.then(res => {
res.json()
})
.then(user => {
console.log(user)
})
.catch(err => {
console.log(err)
})
}`
And my post function on the express server
app.post("/login", (req, res) => {
console.log(req.body)
})
For example, if the object I want to send is {username: "user1", password: "password"}, when I console.log(req.body), I get { '{"username":"user1","password":"password"}': '' } in the console.
How do i fix this so i get the object that I requested?
Because it is JSON format. To parse it you can use:
JSON.parse('{"username":"user1","password":"password"}')
or JSON.parse(req.body)
The approach is fine with JSON.stringify() because it should be posted just like a string to the server. But if you want it to be an object at the backend then you have to parse it back with:
const userObj = JSON.parse(req.body.Data); // it will parse it back as an object

Mock Postman request into Axios?

I'm trying to construct my axios to be able to mimic the postman request but failed. Please help to have a look
const ax = axios.create({
timeout: 30000,
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});
// Attempt register operation
ax.post('https://url/5bc9ff9628d79b6d274165da/update.json', {
body: JSON.stringify({
json: JSON.stringify({ "stat": "Delivered" })
})
})
.then(({ data }) => {
console.log('DEBUG::success!!! data::', data);
})
.catch((err) => {
console.log('DEBUG::err', err);
});
You can make use of the code-generation feature in Postman.
Click on Code (below Save button) > Search for 'Axios' > NodeJS - Axios
Docs for code generation in Postman: https://learning.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets/
2022 Update
Click on </> icon in right side nav bar
Select Axios from drop down

Is this a thunk?

I was googling about Redux thunk and I kind of get the gist of what it's used for and how to make one and as I was about to start making it, I just realized that I may have already made one. I say may because I based my code from boilerplate code made by visual studio when I created a react app using asp.net core as a backend. The code in question:
editLecture: (lecture) => (dispatch) => {
dispatch({ type: EDITING_LECTURE, payload: lecture })
const url = `api/lecture/${lecture.topicID}`
const response = fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(lecture)
}).then(res =>
res.json()
).then(json =>
dispatch({ type: EDITED_LECTURE, payload: json })
)
}
So yeah, is this a thunk? PS: I'm a JS/React/Redux noob so if this comes out as an obvious answer I'm sorry..

Stripe checkout error

I am trying to implement stripe checkout to me store and I get an error saying:
Here is my code:
onToken = (token) => {
fetch('/save-stripe-token', {
method: 'POST',
body: JSON.stringify(token),
}).then(response => {
response.json().then(data => {
alert(`We are in business, ${data.email}`);
});
});
}
Looks like there was an error parsing the object into json. It would be helpful to know what you are calling onToken with.
Make sure to set Content-Type and Accept headers with application/json when making your request:
fetch('...', {
// ...
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
// ...
})
Make sure to always add a catch block to deal with errors. Also I suggest you return the response.json() instead of dealing with right away in the same then block (this is an anti-pattern that does not help in alleviating callback hell).
fetch(...)
.then(response => {
return response.json();
})
.then(data => {
alert(`We are in business, ${data.email}`);
})
.catch(error => {
// Handle the error here in some way
console.log(error);
});

Resources