React direct to external NodeJS route and display data from processed body - node.js

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

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

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 Sequelize Operators with values from JSON body

New to Sequelize and SQL queries in general but wondering there is a simple way to use values sent in JSON body from the client when querying the database. I tried a number of variations of the below without success.
A simple example of the server route looks like this:
builder.post('/', async (req, res) => {
let track_criteria1 = req.body.criteria1;
let track_criteria2 = req.body.criteria2;
const customPlaylist = await req.context.models.Song.findAll({
where: {
[Op.and]: [
{ criteria1: { [Op.gt]: track_criteria1 } },
{ criteria2: { [Op.gt]: track_criteria2 } }
]}
});
return res.send(customPlaylist);
});
module.exports = builder;
For context, the request from the client looks like this:
const handleSubmit = async event => {
event.preventDefault()
updateStatus(PENDING)
const response = await fetch(`http://localhost:8000/playlistbuilder/`, {
method: 'POST',
contentType: 'application/json',
body: JSON.stringify({
criteria1: state.trackCriteria.criteriaOne,
criteria2: state.trackCriteria.criteriaTwo,
})
})
const tracks = await response.json()
setcustomTracks(tracks)
setTimeout(() => {
updateStatus(SUCCESS)
}, 2000)
}
Maybe this is wishful thinking! Right now there is no error but the SQL query logs out like: WHERE ("songs"."criteria1" > NULL AND "songs"."criteria2" > NULL);
Thanks!
If anyone else ends up here. I solved it by moving the contentType into a header. The updated submit handler looks like:
const handleSubmit = async event => {
event.preventDefault()
updateStatus(PENDING)
const response = await fetch(`http://localhost:8000/playlistbuilder/`, {
headers: {
'Content-Type':'application/json'
},
method: 'POST',
body: JSON.stringify({
criteria1: state.trackCriteria.criteriaOne,
criteria2: state.trackCriteria.criteriaTwo,
}),
})
I don't know enough about this yet to explain WHY this works. I'll research that tomorrow, but it is now working.

How to show the success response from node server on react-redux framework

I am making a demo react-redux app for the basic understanding of redux and its server is made on nodeJS. I have made a simple form which gets submitted and the server response is res.send('FORM SAVED'). In front-end, I make the post request but is not able to see the response that returns, be it the success response.
My server controller that responds when form details are saved.
export const postData = (req, res) => {
let p = new PostData();
p.name = req.body.name;
p.emp_id = req.body.emp_id;
p.age = req.body.age;
p.dept = req.body.dept;
p.phone = req.body.phone;
p.gender = req.body.gender;
p.save(((err) => {
if (err){res.send(`Error in uploading: ${err}`);}
else {res.send('Form saved');}
}));
}
This is my action:-
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then((post) => {
console.log('post:', post);
dispatch({
type: NEW_POST,
payload: post
})
})
}
This is how I call this in component after clicking submit:-
onSubmit = (e) => {
e.preventDefault();
let postData = {
name: this.state.name,
emp_id: this.state.emp_id,
dept: this.state.dept,
gender: this.state.gender,
age: this.state.age,
phone: this.state.phone
}
this.props.createPost(postData);
}
I want to get the response string ('Form saved') but I don't know how to read that. Can anyone help? Thanks in advance
fetch returns a raw response object. To get an expected data you should call a .json() method on raw response object which is returned by fetch, like below:
export const createPost = postData => dispatch => {
fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => response.json()) // add this line
.then((post) => {
console.log('post:', post); // you should get an object with `Form saved` or something similar to it
dispatch({
type: NEW_POST,
payload: postData // replace it to the input parameter
})
})
}
Using async/await it becomes more readable:
export const createPost = (postData) => async (dispatch) => {
// send postData to server
const rawResponse = await fetch(`${Config.address}/post`, {
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
// we are done with server but we need one more step
// turn a raw response to readable JS object
const message = await rawResponse.json()
// message from server response
console.log('Message ', message);
// store same object as we sent to server in redux store
dispatch({ type: NEW_POST, payload: postData });
}
Hope it helps

Resources