connecting react frontend with node js rest api - node.js

I'm connecting my react frontend with a rest API from my node js backend folder but once the post request is send i keep getting this
errors
const handleSubmitData = async (event) => {
try {
const { user } = props;
const updatedData = (data) => {
props.updatedUserData(data);
};
await axios.post(`${BASE_API_URL}/api/auth/register`, { ...user, ...updatedData });
Swal.fire('Awesome!', "You're successfully registered!", 'success').then(
(result) => {
if (result.isConfirmed || result.isDismissed) {
props.resetUser();
navigate('/user/login');
}
}
);
} catch (error) {
console.log(error)
if (error.response) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: error.response.data
});
console.log('error', error.response.data);
}
}
};
}

As i can see in your Error Screenshot you have defined email and policy field required in your mongoose Schema. Something like this...
email: {
type: String,
required: true
}
Your server is not getting these two required fields, make sure you are sending those in axios Post Request Properly !

Related

How to perform a GraphQL mutation in ExpressJS with a dynamic value sent from React frontend when building a Shopify App

When I call a simple query from React, the below code with hardcoded values for 123 and NEW NAME work fine.
REACT
const data = useAppQuery({
url: "/api/collection",
reactQueryOptions: {
onSuccess: () => {
setIsLoading(false);
},
},
});
EXPRESS
app.get("/api/collection", async (req, res) => {
try {
const session = res.locals.shopify.session;
const client = new shopify.api.clients.Graphql({ session });
const response = await client.query({
data: `mutation updateCollectionHandle {
collectionUpdate(input: {id: "gid://shopify/Collection/123", title: "NEW NAME"}) {
collection {
title
}
userErrors {
field
message
}
}
}`,
});
res.status(200).send(response);
} catch (err) {
res.status(500).send(err);
}
});
But how do I make a mutation and have the 123 and NEW NAME as dynamic values received from React? Using REST API I simply would add them in to a data field, but with GraphQL in Shopify I don't understand how to pass the values with the useAppQuery function as it doesn't accept the data parameters.

Axios - API returning HTML instead of JSON

I'm developing an application using the MERN stack. As I deployed my demo version on render.com, I faced some issues. Sometimes the Axios request is returning HTML, instead of a JSON file.
ItemController.js
const getItem = async (req, res) => {
const { type } = req.params;
if (!type) {
throw new BadRequestError("Please provide all values");
}
const items = await Item.find({ type: type });
res.status(StatusCodes.OK).json({ items });
};
Request
const authFetch = axios.create({
baseURL: "/api/v1",
});
//Request
const findItems = async () => {
dispatch({ type: LOADING_ITEMS_BEGIN });
let url = "/items";
if (state.currentCategory) {
url = url + "/" + state.currentCategory;
}
try {
const { data } = await authFetch.get(url);
console.log(data);
dispatch({ type: LOADING_ITEMS_SUCCESS, payload: { data } });
} catch (error) {
console.log(error);
dispatch({
type: LOGIN_USER_ERROR,
});
}
};
I've checked the request URL, it's always fine. But it seems like the requests do not even reach the server when it sends back HTML, and I get 200 as a status code.
I tried to trace the request, but couldn't find any clue
Edit: It seems fine using Postman, so something is definitely wrong with the request.

some fields are not send to the database when making a react post request to a node backend api

enter image description here
this is the error ,the data is being shared across from step one enter code hereform up to step five
enter code here
//register user after submit details
const handleSubmit = async (event) => {
event.preventDefault();
try {
const { user } = props
//update image selected to the user
const formData = new FormData();
formData.append('image', files[0]);
const updatedData = {
...user,
image: files[0].name
};
//register user
await axios.post(`${BASE_API_URL}/api/auth/register`, { ...user, ...updatedData });
Swal.fire('Awesome!', "You're successfully registered!", 'success').then(
(result) => {
if (result.isConfirmed || result.isDismissed) {
props.resetUser();
navigate('/user/login');
}
}
);
} catch (error) {
console.log(error)
if (error.response) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: error.response.data
});
console.log('error', error.response.data);
}
}
};
Check the network tab in the browser to see wich data you are sending in the body. If the email is not present in the request, then try to log the props.user

xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden) / cannot delete document

I am using axios for the request of my own api, everything works correctly except the DELETE request, I looked for information about the error but I have not found the solution. when I send the request to the server I get this error: "xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden)".
I put this line of code in Package.Json to avoid problems with CORS:
"proxy": "http://localhost:8080/api"
This would be my api, for the operation I pass the post id by url and the user id:
(I tried it in postman and it works without any problem)
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.userId === req.body.userId) {
await post.deleteOne();
res.status(200).json("the post has been deleted");
} else {
res.status(403).json("you can delete only your post");
}
} catch (err) {
res.status(500).json(err);
}
});
and this is where I consume my api:
const Post = ({ date, _id,userId, description }) => {
const handleDelete = async () => {
try {
await axios.delete('posts/' + _id, { userId: currentUser._id })
} catch (error) {
console.log(error)
}
}
return(
<div onClick={handleDelete }>
//component content
</div>
)
}
export default Post
I solved it, sending a data object to my api (inside that object I put the user id):
const handleDelete = async () => {
try {
await axios.delete('/posts/' + _id, {
data: {
userId: currentUser._id
}
}
)
} catch (error) {
console.log(error)
}
}

PUT request from React to mongodb with Axios

I need some little help. PUT request doesn't work when I send it from React app using Axios. But when I test PUT api from Postman - it works as it suppose to. Server side - node+mongoose+mongodb.
modifyCurrentHaspInfo = (e) => {
if (prompt("Enter password:") === "123456") {
axios.put("/hasp/change", {
data: {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
} else {
alert("Wrong password!");
}
}
When it finds correct id - data in body must be changed. Here is code from server:
//PUT request
app.put("/hasp/change", function(req, res) {
//console.log(req.body);
HaspInfo.findOneAndUpdate({_id: req.body._id}, {$set:req.body}, {new: true}, function(err, hasps) {
if (err) {
res.status(500).send({error: "Could not modify hasp info..."});
} else {
//console.log(hasps);
res.status(200).send(hasps);
}
});
});
It's because your axios is malformed (not what you're expecting at the backend).
The way you're sending data now from axios can be accessed at the backend as
req.body.data
// which will be an object like
{
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
So _id can be accessed like req.body.data._id. Change your request to one of the following (note the differences)
axios.put("/hasp/change", {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
})
Or
axios.put({
url: "/hasp/change",
data: {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
})

Resources