How to post a body correctly in Postman - node.js

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:

Related

Node.js Paypal how to send other data alongside the trigger

I am attempting to send data alongside the code for paypal to the node.js client, but I am not sure where to send that data alongside it.
Here is the client side paypal code:
paypal.Buttons({
// Order is created on the server and the order id is returned
createOrder: (data, actions) => {
return fetch("/api/orders", {
method: "post",
// use the "body" param to optionally pass additional order information
// like product ids or amount
})
.then((response) => response.json())
.then((order) => order.id);
},
// Finalize the transaction on the server after payer approval
onApprove: (data, actions) => {
return fetch(`/api/orders/${data.orderID}/capture`, {
method: "post",
})
.then((response) => response.json())
.then((orderData) => {
// Successful capture! For dev/demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
const transaction = orderData.purchase_units[0].payments.captures[0];
alert(`Transaction ${transaction.status}: ${transaction.id}\n\nSee console for all available details`);
// When ready to go live, remove the alert and show a success message within this page. For example:
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
Here is the server side paypal code:
app.post("/api/orders", async (req, res) => {
const order = await createOrder();
res.json(order);
});
// capture payment & store order information or fullfill order
app.post("/api/orders/:orderID/capture", async (req, res) => {
const { orderID } = req.params;
const captureData = await capturePayment(orderID);
// TODO: store payment information such as the transaction ID
res.json(captureData);
});
//////////////////////
// PayPal API helpers
//////////////////////
// use the orders api to create an order
async function createOrder() {
const accessToken = await generateAccessToken();
const url = `${base}/v2/checkout/orders`;
const response = await fetch(url, {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
intent: "CAPTURE",
purchase_units: [
{
amount: {
currency_code: "USD",
value: "100.00",
},
},
],
}),
});
const data = await response.json();
return data;
}
// use the orders api to capture payment for an order
async function capturePayment(orderId) {
const accessToken = await generateAccessToken();
const url = `${base}/v2/checkout/orders/${orderId}/capture`;
const response = await fetch(url, {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
const data = await response.json();
return data;
}
The issue is there is no req.body.stuff anywhere.
The goal I am trying to achieve, is is when the payment is made, I want to send the data of like the string "potato", Before the actual payment goes through on node. Because potato is a client side variable that will then when used in server retrieve the value of the amount to be paid in node.
Where/how do I put this so I can do this?
Thanks.
How to do it is literally explained in the comments of that client-side code:
return fetch("/api/orders", {
method: "post",
// use the "body" param to optionally pass additional order information
// like product ids or amount
})

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

React direct to external NodeJS route and display data from processed body

i have this fetch request which send some body data to http://localhost:8000/report and then redirects to the same route on server to display data after processing :
const handleGo = async () => {
const employee = {
name: name.current.value,
month: month.current.value,
year: year.current.value,
};
await fetch("http://localhost:8000/report", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(employee),
});
window.location.replace("http://localhost:8000/report");
};
index.json server
const client = require("#jsreport/nodejs-client")("http://localhost:8001");
app.post("/report", (req, res, next) => {
employee.getEmpReport(req, res, next, client);
});
function getEmpReport
const getEmpReport = async (req, res, next, client) => {
const { name, month, year } = req.body; /// processing body data coming from react client
Employee.aggregate([
// doing some MongoDB join with conditions and returning results
]).exec(function (err, employee) {
const dataObject = {
/// setting some data from returned employee
};
client
.render({
template: { name: "/salary/salarySlipTemplate" },
data: dataObject,
options: { reports: { save: true } },
})
.then((response) => response.pipe(res))
.catch(next);
});
};
i want this route to process data and then display data after processing, but when window.location.replace("http://localhost:8000/report"); redirects to the route it says cannot get /report
i think i need a get route but then how can i recieve body data ? i want to be able to recieve the data from client and display it at the same time, how can i do that ?
i should send request from client to jsreport client and send data directly, server should only return the filtered employee:
import jsreport from "#jsreport/browser-client";
jsreport.serverUrl = "http://localhost:8001";
const handleGo = async () => {
const employee = {
name: name.current.value,
month: month.current.value,
year: year.current.value,
};
const response = await fetch("http://localhost:8000/report", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify(employee),
});
const data = await response.json();
const report = await jsreport.render({
template: {
name: "/salary/salarySlipTemplate",
},
data: data,
});
report.openInWindow({ title: "salary slip" });
};

FaunaDB returns empty array (FaunaDB + Netlify + VueJS)

My code is based on the repository - https://github.com/ttntm/recept0r-ts
Code from "\functions\read-all.js":
const faunadb = require('faunadb');
const fnHeaders = require('./_shared/headers.js');
exports.handler = (event, context) => {
const client = new faunadb.Client({
secret: process.env.FAUNA_SECRET,
domain: 'db.fauna.com',
scheme: 'https',
port: '443'
});
const q = faunadb.query;
const headers = { ...fnHeaders };
const origin = event.headers.Origin || event.headers.origin;
headers['Access-Control-Allow-Origin'] = origin ? origin : '*';
return client.query(q.Paginate(q.Match(q.Index('all_users'), false), { size: 500 }))
.then((response) => {
const listRefs = response.data;
const getListDataQuery = listRefs.map(ref => q.Get(ref)); // create new query out of list refs, then query the refs
return client.query(getListDataQuery).then((records) => {
return { statusCode: 200, headers: headers, body: JSON.stringify(records) }
})
})
.catch((error) => {
return { statusCode: 400, headers: headers, body: JSON.stringify(error) }
});
}
Code from "\src\store\modules\data.js":
async readAll({ commit, dispatch, rootGetters })
{
const fn = rootGetters['app/functions'];
const request = await fetch(fn.readAll, { method: 'GET' });
const response = await request.json();
if (response.length > 0) {
commit('SET_ALL_RECIPES', response);
commit('SET_LAST_UPDATED', new Date); }
else {
dispatch('app/sendToastMessage', { text: 'Error loading recipes. Please try again later.', type: 'error' }, { root: true });
return 'error';
}
}
Everything seems to be set. For example, this code works:
client.query(q.CreateCollection({ name: 'someCollection' }))
But can't read any data.
If launch application by "netlify dev" (localhost) - "read-all" returns empty array ("[]").
If launch application by "network" - "read-all" returns default "index.html".
I have no idea what's wrong. Maybe someone give advice...
I found a similar question - Local Netlify function server gives strange response instead of FaunaDB data
Some answer:
"In my experience, one of the most common reasons for this error is a routing problem, which is triggering a 404 response route serving HTML instead of your expected function handler."
This code works:
return client.query(q.Paginate(q.Documents(q.Collection('customers')), { size: 500 }))
.then((response) => {
const listRefs = response.data;
const getListDataQuery = listRefs.map(ref => q.Get(ref)); // create new query out of list refs, then query the refs
return client.query(getListDataQuery).then((records) => {
return { statusCode: 200, headers: headers, body: JSON.stringify(records) }
});
})
.catch((error) => {
return { statusCode: 400, headers: headers, body: JSON.stringify(error) }
});

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

Resources