How can I get the same content in my react native app as in my postman GET? - javascript

I'm communicating with a REST server, which should return ( and this is what I get when I use Postman to request it):
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
},
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
}
]
but this block of code of mine :
await fetch('https://gitroom-backend.azurewebsites.net/api/Event', {
headers: {
Authorization: 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIs',
}
})
.then(res => {
console.log("content"+JSON.stringify(res))
})
}
is returning:
content{"type":"default","status":200,"ok":true,"headers":{"map":{"cache-control":"public, max-age=0","date":"Mon, 25 Nov 2019 13:14:09 GMT","set-cookie":"ARRAffinity=84e8f0e39af3bde1a8c7117e525b046a8722dc904bb8684ace19b555cc8f3590;Path=/;HttpOnly;Domain=gitroom-backend.azurewebsites.net","x-powered-by":"ASP.NET","request-context":"appId=cid-v1:65c12a05-4adc-4521-b71d-69ccdcb78d9f","server":"Microsoft-IIS/10.0","vary":"Accept-Encoding","content-type":"application/json; charset=utf-8","transfer-encoding":"chunked"}},"url":"https://gitroom-backend.azurewebsites.net/api/Event","_bodyInit":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}},"_bodyBlob":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}}}
How can I access the actual content that I want and which Postman is giving me?
EDIT:
MY Postman:

fetchData = async () => {
const response = await fetch(
"YOUR_URL"
);
const json = await response.json();
}
Now render items iterative using constructor of your data set.
and call in your view by,
{item.YOUR_KEY}

Related

CustomHook with multiple functions doesn't work

I am not sure why this customhook doesn't work , I am trying to make a payment Integration to my website but it doesn't return the frame to the other component so i can get the link , here is the code
import React , {useState} from 'react'
import { useEffect } from 'react';
export async function usePayment(data) {
const API = process.env.PAYMOB_API;
const integrationID = 2874212;
const [frame,setFrame] = useState('');
async function firstStep (datas) {
let data = {
"api_key": API
}
let request = await fetch('https://accept.paymob.com/api/auth/tokens' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let token = response.token
await secondStep(token , datas)
}
async function secondStep (token , datas) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": datas.amount * 100,
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let id = response.id
await thirdStep(datas , token , id)
}
async function thirdStep (datas , token , id) {
let data = {
"auth_token": token,
"amount_cents": datas.amount * 100,
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": datas.email,
"floor": "42",
"first_name": datas.name,
"street": "Ethan Land",
"building": "8028",
"phone_number": "00000000000",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": integrationID
}
let request = await fetch('https://accept.paymob.com/api/acceptance/payment_keys' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let TheToken = response.token
let iframURL = `https://accept.paymob.com/api/acceptance/iframes/377194?payment_token=${TheToken}`
setFrame(iframURL)
console.log(frame)
}
useEffect(() =>{
firstStep(data)
},[])
return { frame };
}
export default usePayment;`
I am not sure what is missing here , please need someone to guide me why multiple functions in customhook doesn't work , error message is
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1 - You might have mismatching versions of React and the renderer (such as React DOM)
2 - You might be breaking the Rules of Hooks
3 - You might have more than one copy of React in the same app
and this is the code i use to call the function :
const handleSubmit = async (event) => {
event.preventDefault();
try {
if ( !name || !email || !amount ) {
generateError("Please Fill The Form !")
} else {
const { frame } = await usePayment(datas);
console.log(frame)
// location.href = pay.iframURL;
}
} catch (err) {
console.log(err);
}
};
I expect to get a url to the frame state then pass it to another component
NOTE : that this functions works fine when i add it to the component but its not working as a customhook , i am not sure why
For this use case it would be better not to use a hook, rather just write this as a js function. There's no advantage I can see to using a hook, since you're just waiting for data in useEffect and invoking the 3 api calls after that. Instead just send the payload directly to the async function when needed.
const API = process.env.PAYMOB_API;
const integrationID = 2874212;
async function firstStep (data) {
let data = {
"api_key": API
}
let request = await fetch('https://accept.paymob.com/api/auth/tokens' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
const { token } = await request.json()
return token
}
async function secondStep ({token , data}) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": data.amount * 100,
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
const { id } = await request.json()
return id
}
async function thirdStep ({data , token , id}) {
let data = {
"auth_token": token,
"amount_cents": data.amount * 100,
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": data.email,
"floor": "42",
"first_name": data.name,
"street": "Ethan Land",
"building": "8028",
"phone_number": "00000000000",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": integrationID
}
let request = await fetch('https://accept.paymob.com/api/acceptance/payment_keys' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let TheToken = response.token
let iframURL = `https://accept.paymob.com/api/acceptance/iframes/377194?payment_token=${TheToken}`
return frame;
}
}
export async function handlePayment(data) => {
const token = await firstStep(data);
const id = await secondStep({ data, token });
return await thirdStep({ data, token, id })
}
export default handlePayment;`

Objects are not valid as a React child. If you meant to render a collection of children, use an array

i want to render an email of all the users for testing purpose, In fact i have done that using this method. --- {dataFromApi.map((item, i) => {item.email})} but still it didn't work
const [dataFromApi, setDataFromApi] = useState([]);
const URL = 'http://localhost:5000/users'
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
}
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]);
}).catch( (err) => {
console.log(err);
})
}
return (
<div className="login">
<h1 className="loginTitle">Choose a Login Method</h1>
<p>{dataFromApi}</p>
<div className="wrapper">
.
.
.
.
.
here is the API response
[
{
"id": 1,
"email": "test1234#gm.com",
"password": null
},
{
"id": 2,
"email": null,
"password": null
},
{
"id": 3,
"email": "test#123.com",
"password": "12345678"
},
{
"id": 4,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 5,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 6,
"email": "test#231.com",
"password": "12345678"
},
{
"id": 7,
"email": "NEWtest#231.com",
"password": "123"
}
]
but getting this error
react_devtools_backend.js:4012 The above error occurred in the component:
and
react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {id, email, password}). If you meant to render a collection of children, use an array instead.
Like Adam said in the comments, you are trying to pack a collection of things into a tag meant for a single thing. You should iterate over the list rendering a thing for each item.
{dataFromApi.map((item, i) => <p key={i}>{item.email}</p>)}
I got the answer why i'm not getting the expected output because in this code
const submit = () => {
const data = fetch(URL, requestOptions);
data.then( (userdata) => {
return userdata.json();
}).then( (data) => {
setDataFromApi(data[0]); // this will store only one object into an array
}).catch( (err) => {
console.log(err);
})
}
here setDataFromApi(data[0]) will store only 1 object and to access the email from the object, we have to use only dataFromApi.email else dataFromApi will give only object which we can't render so that's why it is giving an error.

Trying to grab the correct post id from API in order to send message to only that post

In React Javascript - how would I send a message to a post with a specific id? Here's a sample object:
{
"success": true,
"error": null,
"data": {
"post": {
"location": "Bronx, NY",
"willDeliver": false,
"messages": [],
"active": true,
"_id": "5e8d1bd48829fb0017d2233b",
"title": "Schwinn Bicycle",
"price": "3.88",
"description": "This is a 19 speed bicycle, barely used.",
"author": {
"_id": "5e8d1a02829c8e0017c20b55",
"username": "joe1234"
},
"createdAt": "2020-04-08T00:33:24.157Z",
"updatedAt": "2020-04-08T00:33:24.157Z",
"__v": 0,
"isAuthor": true
}
}
}
I must be grabbing the id incorrectly because the message isn't sending to the right post.
I have a useState initialized with an empty string to store the post id so I can pass it into the fetch URL request.
const [postId, setPostId] = useState("");
const response = await fetch(`${API_URL}/posts/${id}/messages`
Here's the code I have so far
const sendMessage = async (token, id, content) => {
try {
const response = await fetch(`${API_URL}/posts/${id}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
message: {
content: content,
},
}),
});
const data = await response.json();
alert("message successfully sent");
return data;
} catch (err) {
console.error(err);
}
};
<form
name="message"
onSubmit={(event) => {
event.preventDefault();
posts.map((post) => {
setPostId(post._id);
});
}}
<label htmlFor="content">Content: </label>
<input
type="text"
name="content"
value={messageContent}
required
onChange={(event) => {
setMessageContent(event.target.value);
}}
/>
<button
onClick={() => {
sendMessage(token, postId, messageContent);
}}
>
Send
</button>
Thanks for any hints or help!

How to put a buffer in an HTTP request?

I’m trying to put a buffer in a request because I have a list of data to import. I want to have success request after one another. The problem I’m encountering is that it waits to upload all data of the request.
Here is the sample data:
[
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const createEngage = async(body) => {
const BASE_URL = '/api/import'
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: body
};
fetch(BASE_URL, requestOptions)
.then(response => response.text())
.then(async result => {
console.log(result);
})
.catch(error => console.log('error', error));
}
What you probably want to do is to loop over your data and use async / await to wait at each iteration. Your implementation of your asynchronous function currently does not await anything. Instead it should await the fetch request and the decoding of the body with response.text().
Check the response for errors and wrap the fetch request in a try...catch block. If an error occurs then the catch block will be executed. Otherwise check the response object for any states or errors you want to include.
const data = [
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const BASE_URL = '/api/import'
/**
* Sends a request for each individual item.
*/
const createEngage = async body => {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body
};
try {
const response = await fetch(BASE_URL, requestOptions);
if (!response.ok) {
alert('Your request has failed');
return null;
}
const text = await response.text();
return text;
} catch(error) {
alert('Your request caused an error');
}
};
/**
* Loop over each item and call createEngage.
* Wait for the request to finish and continue.
*/
const createMultipleEngages = async data => {
for (const item of data) {
const result = await createEngage(item); // This will make the loop wait every time.
console.log(result);
}
};
// Call the function and start looping.
createMultipleEngages(data);

Expressjs Post-request is not getting recognized | 404-Error

I want to implement paypal to my website, but I am stuck with this. Always when I try to do a post request (also tried with postman), I dont get an answer which is just the normal 404 error-page. The console is showing no error, so I guess the post request is not getting recognized.
What could be the problem and how can I fix it?
server.js
//payment
app.post("/pay", (req, res) => {
// payment data
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "product1",
"sku": "001",
"price": "350.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "350.00"
},
"description": "test"
}]
};
// create payment
paypal.payment.create(create_payment_json, (error, payment) => {
if(error) {
console.log("payment not successful");
console.log(error)
} else {
console.log("payment successful");
console.log(payment);
}
})
})
products.ejs
<form action="/pay" method="post">
<input type="submit" value="add to cart" onclick="window.location.href='/pay'"/>
</form>
Couple of things you need to make sure
Make sure you are sending the post request to the correct port, just incase your express server isn't hosting the actual site as well. If it is then don't worry about the port
You can use js to send the request to prevent the page from refreshing.
const form = document.querySelector('form')
form.addEventListener('submit', async function(e) {
e.preventDefault()
const port = 3000 //make sure this is the port your express erver is listening on
const formData = new FormData(e.target)
const itemId = formData.get('itemId')// You can store the items id in the name attribute of an input
const response = await fetch(`http://localhost:${port}/pay`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
})
})
const data = await response.json()
console.log(data) // The response you would get from the server

Categories

Resources