send body with "GET" method in axios - node.js

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

Related

Make a POST request and fetch posted data back to client

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/

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

How to post a body correctly in Postman

I try to make a post request to an api but, api returns error. Although I thought about it for a long time, I could not find the cause of the error.
I think the error is due to not creating the body correctly because when I send empty array as items array the code works.
API DOCUMENTATION:
Here is my request:
module.exports.createOrder = (token, paymentId, items, callback) => {
const url = urlBase;
request(
{
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
Authorization: `Bearer ${token}`,
},
body: {
secretKey: `${secretKey}`,
paymentId: paymentId,
items: items,
},
},
(error, response) => {
if (error) {
Sentry.captureException(error);
callback(errMessage, undefined);
} else {
const data = response.body;
callback(undefined, data);
}
}
);
};
Here is test values:
const testToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyM2RmYjg4NDA4M2IwMDAyNDNjYzRhNyIsImlhdCI6MTY0ODIyOTI1NywiZXhwIjoxNjQ4MzE1NjU3fQ.9fgR3ei81vsHVMhSi8VwEyE2WMgFIMthm0PF9_zrqjw"
const paymentId = "pi_1Dq2f62eZvKYlo2Cy1moIb0G"
const variant = {
variations_values: {
color:'Black',
size:'42'
},
price:495,
product_id: "883360511078"
}
const productId = "82936941"
const quantity = 1
const item = {
variant:variant,
productId:productId,
quantity:quantity
}
let items = [item]
orderRequests.createOrder(testToken, paymentId, items, (err, data) => {
if(data){
console.log(data)
} else{
console.log(err)
}
})
I get internal server error as a response when I post these test values, but If I post an empty array as items, api does not return internal server error. What is the problem, any help?
Internal Server Error Response when I send an array with post body:
Expected request when I send an empty array with post body:

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"
};

Why is expressjs POST request returning [object Object]?

app.post("/api/orders", async(request, response) => {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db(dbName);
// Use the collection
console.log("search options " + json(request));
const col = db.collection("Orders");
// const inserted = await col.insertOne();
response.send("thanks")
} catch (err) {
console.log(err.stack);
}
});
/
let orderData = {subject: "subject", location: "location", price:"price", spaces: "spaces"};
const optionsPOST = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(orderData)
};
console.log(JSON.stringify(orderData))
fetch("/api/orders", optionsPOST);
I am trying to post some data that then is added to mongodb atlas, however, when I post my data I get undefined.
Try using a simple fetch request
fetch('/api/orders', optionsPOST)
.then(response => response.json())
.then(data => console.log(data));
This should also help: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Resources