React Native fetch method makes multiple API calls on the server - react-native

I am using fetch method to make API calls on the server and noted it is making multiple requests at the same time and due to this it increases 30% RPM on the server
Can someone please help in preventing multiple calls and understanding why is it happening?
Below you can see React Native code and server logs
React Native Code
fetch(url, {
method: "GET",
headers: {
'Accept': "application/json",
'Content-Type': "application/json"
}
}).then((resp) => {
if (resp.status === 200) {
resp.text().then(function(data) {
var resData = JSON.parse(data);
}
}
}
Server Logs
[Wed Jan 25 12:14:08.323939 2017] [:error] [pid 13832] 2017-01-25 12:14:08.323658 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}
[Wed Jan 25 12:14:08.631057 2017] [:error] [pid 14306] 2017-01-25 12:14:08.630777 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}
[Wed Jan 25 12:14:09.103341 2017] [:error] [pid 14307] 2017-01-25 12:14:09.102915 URL: /driver/upcoming-bookings/ User: {'id': '', 'email': 'Anonymous'} HTTP Method: GET Params: {u'imei': u'359375062977098'}

Related

Donwload file with POST method in React Native and Expo

How can I download a file using the POST method along with some headers and data (of the type: "content-type: application/x-www-form-urlencoded") in React Native?
When I send a request to the URL, the following is returned in the Response Header:
content-disposition: attachment; filename="PAPR_Pginas_Web_2.pdf"
content-type: application/pdf
date: Sun, 07 Aug 2022 13:59:00 GMT
last-modified: Thu, 01 Jan 1970 00:00:00 GMT
server: Apache
strict-transport-security: max-age=86400
x-powered-by: JSF/1.2
x-xss-protection: 1; mode=block
I'm using this code:
const donwloadPDF = async (uri) => {
const downloadInstance = FileSystem.createDownloadResumable(uri, FileSystem.documentDirectory + "file.pdf");
const result = await downloadInstance.downloadAsync();
if (result.status === 200) {
Sharing.shareAsync(result.uri, { dialogTitle: "Share or Save" });
} else {
console.log("Failed to Download");
}
};
const getFile = async (payload) => {
try {
const response = await fetch(URL, {
method: "POST",
headers: headers2,
body: formBody(payload),
});
const content = await response.json();
donwloadPDF(content); // Some URI
} catch (error) {
console.error(error);
}
};
But is returned the error: JSON Parse error: Unrecognized token '%'

Using CURL with discord.js and 5sim API

Im trying to make a command for my discord bot, so I can get a verification code for any kind of account from 5sim via their api... I think im very close since some of my code worked in https://reqbin.com/req/c-vdhoummp/curl-get-json-example... but im having trouble implementing it into my command! This is my first time using Curl so im not too familiar, but I was wondering if anyone could give me some help with my broken code?
const Discord = require(`discord.js`)
const curl = require(`curl`)
module.exports = {
name: `buynumber`,
description: `buys a phone number!`,
async execute(message) {
const response = curl 'https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo',
{
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
}; data = await response.json()
message.channel.send(data.number)
}}
the current error im facing is
[Sun Sep 12 2021 21:26:16] [LOG] Initializing Startup!
[Sun Sep 12 2021 21:26:16] [ERROR] (node:12692) UnhandledPromiseRejectionWarning: C:\Users\manof\Desktop\Main Bots\Celly Bot\commands\buy.js:8
const response = curl "https://5sim.net/v1/user/buy/activation/cambodia/any/discord",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
all help would be greatly appreciated!
can you try doing
const response = curl('https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo', {
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
});
const data = await response.json();
Because your syntax is incorrect.
You're trying to call the function curl.get in the curl package and hence it requires you to call it via () this is a simple syntax error and can be fixed like so:
let data;
const response = curl.get('https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo',
{
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
});
data = await response.json()
I suggest you to read the examples given here

pass sessions saved in cookies with post() automatically angular

I have seen a few bug reports on github but couldn't figure out my issue. I have cookies that the server sets. Now during POST method,I want to pass this data back to the server. It is an Observable because response from the server will determine further steps to take. Note that I have no access to the backend but CORS and credentials are set. My current code is:
public logout () : Observable<any> {
/*
Send a clear session request to cbase
*/
let vm : any = this;
const httpPostOptions =
{
headers:
new HttpHeaders (
{
"Content-Type": "application/x-www-form-urlencoded"
}),
withCredentials: true
};
return new Observable((observer) => {
vm.http.post(
Config.syncGatewayLoginStage + 'logout/', httpPostOptions
).subscribe(
data => {
observer.next(data);
},
err => { observer.error(err); console.log(err); },
() => {
observer.complete();
}
);
});
}
The server responds with error 500 that the session doesn't exist and of course, I see no session cookies passed to the server in the request header even though I see cookies set.
The server response is:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Connection: keep-alive
Content-Length: 1406
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Wed, 20 Feb 2019 10:09:29 GMT
Vary: Origin
X-Content-Type-Options: nosniff
X-Powered-By: Express

(Next.js, Express session) New session for every request made inside getInitialProps

I am trying to make Express session work with Next.js, and have successfully done so on the client side, but I am having trouble with API calls made from inside getInitialProps.
Note: I am using isomorphic-unfetch to make API calls. My Next.js installation runs on localhost:3000, my Express server on localhost:5000.
Here is an example of a client side API call (outside of getInitialProps):
componentDidMount() {
fetch('/path/to/endpoint', {
method: 'GET',
credentials: 'include',
}).then((res) => console.log(res));
}
I'm logging res here because I wanted to see the headers. Turns out this request has an empty headers object. If i resolve the promise I get the data I requested though. The session ID from this call stays consistent on the server even if I refresh the page. Everything is working as expected here.
Here is an example of an API call inside getInitialProps:
static async getInitialProps(ctx) {
fetch('/path/to/endpoint', {
method: 'GET',
credentials: 'include',
}).then((res) => console.log(res.headers));
}
Again, logging to see the headers. This response has headers, they look like this:
Headers {
_headers:
{ 'x-powered-by': [ 'Express' ],
'access-control-allow-origin': [ 'http://localhost:3000' ],
vary: [ 'Origin, Accept-Encoding' ],
'access-control-allow-credentials': [ 'true' ],
'x-frame-options': [ 'SAMEORIGIN' ],
'x-xss-protection': [ '1; mode=block' ],
'set-cookie'['YgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS','connect.sid=s%3AYgJGcZPBgbE_nEqqLZpw0ba0pyaf2eNS.Oye%2F7%2BsyXrrLJwphEJ3nq3yMkBhM3%2Fm4PCl9KIV%2FTzA; Path=/; Expires=Sun, 05 Aug 2018 15:56:52 GMT; HttpOnly' ],
'content-type': [ 'application/json; charset=utf-8' ],
'content-length': [ '246' ],
etag: [ 'W/"f6-82FKQ+ERtkxLiKa8hEIeY4kgGgE"' ],
date: [ 'Sun, 22 Jul 2018 15:56:52 GMT' ],
connection: [ 'close' ] } }
As you can see there is connect.sid (express session ID) in my set-cookie header, but the problem is that the connect.sid cookie changes whenever I refresh the page and does not match the session ID of client side API calls (which stays the same even after refreshing the page).
My session object on the Express server looks like this:
app.use(
session({
resave: false,
name: 'connect.sid',
saveUninitialized: false,
secret: SESSION_SECRET,
unset: 'destroy',
cookie: {
maxAge: 3600000 * 24 * 14,
secure: false,
},
store: new MongoStore({
url: mongoUrl,
autoReconnect: true,
}),
})
);
If anyone has an idea how I can make API calls from inside getInitialProps work with express session I'd appreciate the input! Thank you in advance.
I found the solution. Instead of using credentials: 'include' I had to send the session cookie in the request header. Here's a working request inside getInitialProps.
static async getInitialProps(ctx) {
const res = await fetch('path/to/endpoint', {
headers: {
cookie: ctx.req.headers.cookie,
},
});
const user = await res.json();
return { user };
}

WebPushError: Received unexpected response code - GCM

I am using web push to enable push notifications for app.
webPush.setGCMAPIKey('my-gcm-api-key');
app.post('/sendNotification', function(req, res) {
console.log(req.body)
payloads[req.body.endpoint] = req.body.payload;
webPush.sendNotification(req.body.endpoint
, {
TTL: req.body.ttl,
}
)
.then(function() {
console.log('mest')
res.sendStatus(201);
})
.catch(function(err){
console.log(err)
});
});
I am getting below error during the sendNotification api call.
{ [WebPushError: Received unexpected response code]
name: 'WebPushError',
message: 'Received unexpected response code',
statusCode: 400,
headers:
{ 'content-type': 'text/html; charset=UTF-8',
date: 'Thu, 22 Sep 2016 09:22:31 GMT',
expires: 'Thu, 22 Sep 2016 09:22:31 GMT',
'cache-control': 'private, max-age=0',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '1; mode=block',
server: 'GSE',
'alt-svc': 'quic=":443"; ma=2592000; v="36,35,34,33,32"',
'accept-ranges': 'none',
vary: 'Accept-Encoding',
connection: 'close' },
body: '<HTML>\n<HEAD>\n<TITLE>UnauthorizedRegistration</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>UnauthorizedRegistration</H1>\n<H2>Error 400</H2>\n</BODY>\n</HTML>\n' }
Please let me know if anyone came across this issue.