Make a POST request and fetch posted data back to client - node.js

I need assistance in fetching data back to client as soon as it is posted to the database without reloading the page. The structure I have at present only shows the posts on page reload. Below are my codes.
const [pst, setPst] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
const v2 = PST_REGEX.test(pst);
if (!v2) {
// setErrMsg("Invalid Entry");
return;
}
try {
const response = await axios
.post(DASHBOARD_URL, JSON.stringify({ pst }), {
headers: { "Content-Type": "application/json" },
withCredentials: true,
})
} catch (err) {
console.log(err)
}
};
Post Controller
const handleNewPost = async (req, res) => {
const { pst } = req.body;
if (!pst) return res.status(400).json({ message: "Field cannot be blank" });
try {
//create and store the new post
const result = await Userpost.create({
post: pst,
});
console.log(result);
res.status(201).json({ success: `New post ${pst} created!` });
} catch (err) {
res.status(500).json({ message: err.message });
}
};

There are some ways from which you can achieve your solution.
Method 1:
You can return newly created data from backend as success response. Lets assume you got response as follow:
{
"message": "Data created Successfully",
"status" : "201",
"data": [{
"id": "1234",
"title": "Blog title",
"description" : "Blog description"
}]
}
Then you can simply add response to you previous state as:
setPst([...pst, ...message.data]) // message.data is response from your endpoint
Method 2:
You can use socket io for real time experience: https://socket.io/

Related

why I get an empty request body express

Router
router.patch("/fav/:id", getFav);
controller
const getFav = async (req, res) => {
const { favToadd } = req.body;
const { id } = req.params;
try {
const Users = await User.findById(id);
console.log("body : ", req.body); // body : {}
const fav = await User.findByIdAndUpdate(id, {
$set: { favorite: [...Users.favorite, favToadd] },
});
res.send(fav);
} catch (error) {
console.log("err ", error.message);
}
};
//Function to add favorites
const response = await fetch(
`http://localhost:4000/api/user/fav/${currentUser._id}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prd: product.props }),
}
);
};
the item gets saved to MongoDB as null and then I take look at the req body it's empty,
my goal is to add an object to the favorite properties in MongoDB document
but it gets saved as null
try different methods but nothing works I don't think I get a body from the patch request
don't know if the problem with it or in the communication between the front and the back end it's
my first app so hopefully, the problem is in this line of code not in another part,
when I send it from postman with raw JSON it Works and gets saved at MongoDB with the properties I set

send body with "GET" method in axios

Is there anyway to send body with GET method in axios? because in postman it is possible. My backend code as below:
I'm using express.js + sequelize
const c_p_get_all = async (req, res) => {
const { category } = req.body;
const sql = `select p.id, p.p_image, p.p_name, p.p_desc, p.p_prize, p.p_size, c.c_name, cl.cl_name
from products as p
inner join collections as cl on cl.id = p.p_collection_id
inner join categories as c on c.id = cl.cl_category_id
where c.c_name = ?
order by p."createdAt" desc;`;
try {
const getData = await Product.sequelize.query(sql, {
replacements: [category],
});
if (getData[0] != "") {
res.status(200).send({
s: 1,
message: "success retrive all products",
data: getData[0],
});
} else {
res.status(404).send({
s: 0,
message: "data not found",
});
}
} catch (err) {
res.status(500).send({
message: err,
});
}
};
My Frontend with react.js + axios
const test = "woman";
axios({
headers: {
"content-type": "application/json",
},
method: "GET",
url: "http://localhost:3001/api/v1/product",
data: { category: test },
})
.then((value) => console.log(value))
.catch((error) => console.log(error.response));
It always goes to status 404, but in postman its working, I've tried to search this problem, but no clue. So is there anyway to do it in axios, or should I change my backend to POST method or change req.body to req.query?
I changed to query parameters and it worked

Using React, NodeJS, and Postgres: Having trouble being able to delete and updating todos

I am creating simple todo app with postgre and react.
The server side the delete and update are defined as below.
app.put("/todos/:id", async (req, res) => {
try {
const { id } = req.params;
const { description } = req.body;
const updateTodo = await pool.query(
"update todo set description = $1 where todo_id = $2",
[description, id]
);
res.json("todo updated !!");
} catch (error) {
console.error(error.message);
}
});
// delete todo
app.delete("/todos/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query("delete from todo where todo_id = $1", [
id,
]);
res.json("todo deleted !!");
} catch (error) {
console.error(error.message);
}
});
On the front end (React) this is how I am calling the update and delete
const updateDescription = async () => {
try {
handleClose();
const body = { description };
const response = fetch(`http://localhost:3000/${todo.todo_id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
} catch (error) {
console.log(error.message);
}
};
Delete todo is in the other component.
const deleteTodo = async (id) => {
try {
const deleteTodo = await fetch(`http://localhost:3000/${id}`, {
method: "DELETE ",
});
console.log(deleteTodo);
setTodods(todos.filter((todo) => todo.todo_id !== id));
} catch (error) {
console.log(error.message);
}
};
So when I am doing delete or put request its not updating it in the DB.
On the browser console I am getting this error.
Failed to execute 'fetch' on 'Window': 'DELETE ' is not a valid HTTP method.
Edited
Response {type: "cors", url: "http://localhost:3000/3", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:3000/3"
__proto__: Response
For insert todo its working but for delete and put request its not updating in the database.
So can somebody tell me whats going wrong here ?
There is a space after DELETE, correct it should work properly. Even if its a simple todo App, its always good practice to create an enum or const when we are dealing with fixed string, i.e., we know the string would not change so that we can have consistency and skip over these kind of issues.
const METHOD = {
GET: "GET",
PUT: "PUT",
POST: "POST",
DELETE: "DELETE"
};

MissingRequiredParameter: Missing required key 'thingName' in params

In my application backend is node.js and the frontend is react.js,
backend developer has given API we have to pass that in the body, in postman I am getting this response
How to pass raw data in the body using GET API, I have tried to pass data but I am getting an error
state = {
thingName: "",
deviseId: " ",
policyName: " ",
};
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
console.log(e.target.value);
};
handleSubmit = (e) => {
e.preventDefault();
const certparms = JSON.stringify({
"thingName": this.state.thingName,
"policyName": this.state.policyName,
"deviseId": this.state.deviseId
});
console.log(certparms)
axios.get('http://10.84.1.140:3000/cer/create/',certparms,{
headers: {
"Content-Type": "application/json"
},
})
.then(function(response){
console.log(response);
if (response.ok) {
alert("success");
} else {
alert("fail");
}
})
.catch(function (error) {
console.log(error);
});
};
I am getting the following error in node.js logs
please give any suggestions.

Multer image upload patch request

I have a code to upload a form with some field name & a single image in nodejs using multer. Everything works fine when a new file is being uploaded on the POST request. Also, the PATCH request for changing the image is working fine. But, the issue goes that if I need to only change the image, not the service_name, it nullifies the field instead of retaining the previous name provided while a new POST was created.
PATCH REQUEST
exports.editService = async (req, res) => {
const { id } = req.params;
const { service_name } = req.body;
const updates = {};
if (req.body) {
updates.service_name = service_name;
}
if (req.file) {
const service_pic = req.file.filename;
updates.service_pic = service_pic;
}
try {
const updated_data = await Services.findOneAndUpdate({ _id: id }, {
$set: updates
},
{
new: true
}
);
if (!updated_data) {
res.status(404).json({ message: "Data does not exist" });
return;
}
res.status(200).json({ message: "Data updated", result: updated_data });
} catch (error) {
res.status(500).json({ message: "Internal server error", error });
}
}
In the PATCH/PUT request, the service_name is always null.
Postman result:
{
"message": "Data updated",
"result": {
"_id": "5f3648f8aefb2978e8f82d94",
"service_name": null,
"service_pic": "service_pic-1597396108999TIME-CLOCK-service.png",
"createdAt": "2020-08-14T08:19:04.013Z",
"updatedAt": "2020-08-14T09:08:29.012Z",
"__v": 0
}
}
Not sure where I am handling it wrong. Any help to rectify this is appreciated.

Resources