Reputation: 629
I feel like this should be a duplicate...If it is I'm not finding the correct thread.
I have an Express API
(using mongoose
) on a server with React
front end. The API should return a JSON
to the client.
Problem: It works fine with Postman
but returns the wrong JSON
in React
What I'm sending in Postman
(this generates a correct response):
{"fileHashValue"
:
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
Server Code:
app.get("/userData", function(req, res) {
const fileHashValue = req.body.fileHashValue;
UserData = UserData.findOne(
{
fileHashValue
},
function(err, userdata) {
res.json({
userdata
});
}
);
});
Client Code:
componentDidMount() {
axios
.get(
"http://ec2-52-53-190-3.us-west-1.compute.amazonaws.com:3000/userData",
{
fileHashValue:
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
)
.then(res => {
console.log(res.data);
});
}
It seems like this should all work, but its responding as if I had sent a blank request. IE, if I send a blank request in Postman
it gives me the same result that I'm logging in React
. Any help is appreciated, thanks!
Upvotes: 2
Views: 497
Reputation: 7492
The function axios.get()
is expecting a request config as the second parameter (not your raw params).
You can set your params as follows:
axios.get("http://ec2-52-53-190-3.us-west-1.compute.amazonaws.com:3000/userData", {
params: {
fileHashValue: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
})
.then(res => {
console.log(res.data);
});
A more detailed explanation : https://flaviocopes.com/axios/#get-requests
As the other answer mentioned, using the get
verb may not fit your needs. Get is mostly used to fetch a ressource and is not able to contain a body. Using post
can prevent this. Post is mostly used to create a ressource and can have a body :
axios.post("http://ec2-52-53-190-3.us-west-1.compute.amazonaws.com:3000/userData", {
params: {
fileHashValue: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
})
.then(res => {
console.log(res.data);
});
If your objective really is to simply get an element, I suggest changing your routes architecture to include the id that you are attempting to get in the url :
axios.get("http://ec2-52-53-190-3.us-west-1.compute.amazonaws.com:3000/userData/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", {})
.then(res => {
console.log(res.data);
});
And adapt your backend :
app.get("/userData/:id", function(req, res)
The id will then be accessible in req.params.id
Upvotes: 3
Reputation: 629
As per the instructions in this thread, it is not recommended to .get (really at all). As a rookie, I never recall any of the tutorials mentioning this.
The answer to the question is to switch the client and server logic both to axios.post
and send the json
as shown in the original post.
Upvotes: 1