Is there a way to stop reactjs status page from showing - node.js

I am building an ecommerce with mern stack
When I make request from react to node and it fails it show the status code with error on the page.
is there a way to prevent this from happening
enter image description here
React code
export const createCategories = async(name, token) => {
return await axios.post(
`${process.env.REACT_APP_SERVER_APP_URL}/api/category`,
name,
{
headers: {
'x-header-token' : token
}
}
)
}
const handleSubmit = async(e) => {
e.preventDefault();
setLoading(true)
try{
createCategories(category, localStorage.getItem('token'))
.then(res => {
console.log(res)
setLoading(false)
setCompleted(true)
setCreateCategory(res.data)
});
}catch(err){
setError(true)
setErrorMsg({
"msg": err.response.data
})
}
}
nodejs code
try{
const {name} = req.body;
const category = await new Category({ name, slug: slugify(name)}).save();
res.json({'msg': "Category Created"})
}catch(err){
res.status(400).send("Create Category Failed...")
console.log(err)
}

you should use catch block
createCategories(name,token).then(res => {
// if success in response
}).catch(error => {
// if error in response
})

Related

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)
}
}

How to clear field after submittion in React with useState

I am working on a Mernstack application, everything in my application is working well except the input field that doesn't clear after submission.
my Component
const [comments, setCommentData] = useState([]);
const onSubmit = useCallback(
(e) => {
e && e.preventDefault();
axios
.post(
"http://localhost:9000/events/" +
props.match.params.id +
"/eventcomment",
{ name: name, description: eventDescription }
)
.then(function (response) {
console.log("response", response.data.eventcomments);
onPageLoad();
})
.catch(function (error) {
console.log(error);
});
},
[props.match.params.id, name, eventDescription]
);
I tried doing this but it didn't work.
setCommentData("");
The initial state is [], so you should restore it to the same initial content:
setCommentData([]);

How to pass users' data from nodeJS to reactJS using Express/Mysql

I need to pass author's email in my posts. I though I can do it by joining tables in my posts route, but it doesn't really work.
Here is my route :
router.get("/posts", async (req, res) => {
const { id } = req.session.user;
//const usersPosts = await user.$relatedQuery("posts");
try {
const user = await User.query().findById(id);
if (!user) {
return res.status(401).send("User was not found");
}
const posts = await Post.query()
.select([
"users.email",
"images.name",
"posts.category",
"posts.title",
"posts.description",
"posts.created_at"
])
.join("images", { "posts.image_id": "images.id" });
.join("users", { "posts.user_email": "users.email" });
console.log("it worked");
return res.status(200).send({ posts: posts });
} catch (error) {
console.log(error);
return res.status(404).send({ response: "No posts found" });
}
});
Here is code with my axios fetching the route :
function Home(props) {
const [posts, setPosts] = useState([]);
const getPosts = async () => {
try {
let response = await axios.get("http://localhost:9090/posts", {
withCredentials: true
});
console.log(response.data.posts);
setPosts(response.data.posts);
} catch (error) {
console.log(error.data);
}
};
useEffect(() => {
getPosts();
}, []);
And this is how I tried to return it:
{posts.map((post, index) => {
return (
<>
Author:<br></br>
<small>{post.user_email}</small>
</p>
<p>
Category:<br></br>
<small>{post.category}</small>
</p>
<p>
Description:<br></br>
<small>{post.description}</small>
</p>
<p>
Created: <br></br>
<small>{post.created_at}</small>
Everything works except the fetching Author.
a typo its user_email not users_email
your sending email in the value assingned to user_email and in front end using users_email

POST request with Axios not sending data to my server

Here is my React code for the form submission:
const handleSubmit = (e) => {
e.preventDefault();
console.log('item:', item);
Axios.post('http://<MY_SERVER>/item/add', {name:item})
.then(response => console.log(response))
.catch(err => console.log(err));
};
and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save()
.then(item => {
res.json({msg: 'success'});
})
.catch(err => console.log(err));
});
When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required
So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.
I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');
function sendFormUrlEncodedData() {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with form url using querystring node package for it.
axios
.post('https://reqres.in/api/users', qs.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
function sendJSONData() {
const headers = {
'Content-Type': 'application/json'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with JSON, so stringifying it.
axios
.post('https://reqres.in/api/users', JSON.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
sendFormUrlEncodedData();
sendJSONData();
First of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';
constructor() {
this.item = {
name: ''
}
}
handleSubmit(event) {
console.log('item:', this.item.name);
event.preventDefault();
axios.post('http://<MY_SERVER>/item/add', this.item)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}

Resources