I am trying to get playerid for Onesignal, while doing that it is working strangely.
onIds = async (device) => {
console.log("Device info: ", device.userId);
let playerid = device.userId;
AsyncStorage.setItem('playerid', playerid);
//this.setState({device_id: playerid})
alert(playerid);
}
the above code gives me this error, but in alert I am getting the player id. check the picture attached.
Please help me resolve this. Thanks in advance.
Like you, I tried a lot, but I could not at least not in the conventional ways, I chose to do the following, saving the ID in the BD directly from the function
async onIds(device) {
let uri = await AsyncStorage.getItem('uri');
let token = await AsyncStorage.getItem('token');
try {
let formData = new FormData();
formData.append(
'PNToken',
JSON.stringify({
PushNotificationsID: device.userId
})
);
await fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Authorization: 'Bearer ' + token
},
body: formData
});
} catch (e) {
console.warn(e);
}
}
Related
have a good time! I use axios to send a post request to the api http://freerealapi.com/ I work based on the document but it gives me an error 400 What should I do?
const buildDiscount = async token => {
let data = new FormData();
data.append('title', keyCodes);
data.append('text', 'test text');
data.append('image', file);
data.append('tags', 'one,two,three');
try {
const res = await axios.post('https://api.freerealapi.com/panel/blogs/', data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${token}`,
},
})
console.log(res.data);
} catch (error) {
console.log(error.response);
}
}
This function is most probably missing those 2 extra variables ( keyCodes, file ), can you provide those inputs to the function? That's probably the reason why the request is being malformed.
So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!
After upgrade Expo SDK version from 41.0.0 to 43.0.0 I got a problem with uploading images to server. Error description: No suitable URL request handler found for ph-upload://A354049E-57C1-4478-B5C0-1DF56886F1AD. What I have noticed is that in error description I see ph-upload:// but if I log my photo it contains this: "uri":"ph://A354049E-57C1-4478-B5C0-1DF56886F1AD","name":"IMG_3702.JPG","type":"photo". The difference is ph-upload:// and ph://.
This is my code:
const onSubmitPress = async () => {
await setLoadingIndicator(true);
let formData = new FormData();
formData.append('title', textTitle);
formData.append('description', textDescription);
formData.append('latitude', latitude);
formData.append('longitude', longitude);
formData.append('photoAuthor', photoAuthor);
formData.append('textAuthor', textAuthor);
formData.append('landscapeType', landscapeType);
formData.append('region', region);
route.params?.data?.map((image, index) =>
formData.append(`photo[]`, {
uri: image.uri,
name: image.filename,
type: image.mediaType,
}));
route.params.data = undefined;
const jwtToken = await SecureStore.getItemAsync('JWT');
let responseTypes = await fetch('https://beautiful-places.ru/api/upload_place', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;',
'API-Access-Key': '******',
'Authorization': 'Bearer ' + jwtToken
},
body: formData
})
}
Before upgrade everything worked as expected.
In my case I provided incorrect type of image, it somehow worked with expo ver. 41, but in ver. 43 it doesn't work. This code works fine:
import mime from "mime"; //mime library helps to check type of image.
let formData = new FormData();
formData.append('title', textTitle);
formData.append('description', textDescription);
formData.append('latitude', latitude);
formData.append('longitude', longitude);
formData.append('photoAuthor', photoAuthor);
formData.append('textAuthor', textAuthor);
formData.append('landscapeType', landscapeType);
formData.append('region', region);
photos?.map((image, index) =>
formData.append(`photo[]`, {
uri: image.uri,
name: image.uri.substring(image.uri.lastIndexOf('/') + 1, image.uri.length),
type: mime.getType(image.uri), // after this change problem has gone
})
);
const jwtToken = await SecureStore.getItemAsync('JWT');
let responseTypes = await fetch('https://some-url/api/upload_place', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'API-Access-Key': 'SomeKey',
'Authorization': 'Bearer ' + jwtToken
},
body: formData
})
presently I am attempting to make 2 different api calls one after the other within 1 java/nodejs script. It seems after my first function runs successfully, the second one errors with the following:
FetchError: request to failed, reason: socket hang up;
type: 'system',
errno: 'ECONNRESET',
code: 'ECONNRESET'
Below is a code snippet of what I have tried thus far:
const fetch = require("node-fetch");
const formData = require("form-data");
const fs = require("fs");
//const express = require("express");
var apiName = "<LOCAL SYSTEM FILE TO UPLOAD>";
var lookupName = "<LOCAL SYSTEM FILE TO UPLOAD>";
var accessToken = "Bearer <ACCESS TOKEN>";
var url = '<URL API #1>';
var url2 = '<URL API #2>;
var headers = {
'Accept': 'application/json',
'Authorization': accessToken,
};
const form = new formData();
const buffer2 = fs.readFileSync(lookupName);
const buffer = fs.readFileSync(apiName);
const uploadAPI = function uploadAPI() {
form.append("Content-Type", "application/octect-stream");
form.append('file', buffer);
fetch(url, {method: 'POST', headers: headers, body: form})
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
};
const uploadLookup = function uploadLookup() {
form.append("Content-Type", "application/octect-stream");
form.append('file', buffer2);
fetch(url2, {method: 'PUT', headers: headers, body: form})
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
};
if (!apiName !== true) {
uploadAPI()
} else {}
if (!lookupName !== true) {
console.log("Uploading Lookup File");
uploadLookup()
} else {}
I tried using a "setTimeout" function which does not seem to work as I would have liked it to. My best guess is each API call would need to be it's own separate socket connection? Any help with getting me in the right direction is appreciated.
Promise.all([
fetch(url),
fetch(url2)
]).then(function (res) {
// Get a JSON object from each of the responses
return res.json();
}).then(function (data) {
// do something with both sets of data here
console.log(data);
}).catch(function (error) {
// if there's an error, log it
});
i am new at react native. I fetch data on Firebase but i want to fetch it JSON file. My JSON file like this: enter image description here
how can i change firebase url to my php json url?
PLEASE HELP ME
This is my code:
return async (dispatch, getState) => {
// any async code you want!
// const userId = getState().auth.userId;
try {
const response = await fetch(
'https://shopapp-f9964.firebaseio.com/products.json'
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
const resData = await response.json();
const loadedProducts = [];
for (const key in resData) {
console.log(resData[key].description);
loadedProducts.push(
new Product(
0,
0,
resData[key].product_image,
resData[key].description,
resData[key].price,
)
);
}
dispatch({
type: SET_PRODUCTS,
products: loadedProducts,
//userProducts: loadedProducts.filter(prod => prod.ownerId === userId)
});
} catch (err) {
// send to custom analytics server
throw err;
}
};
Here is the way to get from API (or Json response).
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Here is the official docs, it really helps for you to understand data from JSON file
https://reactnative.dev/docs/network
here is the working example on Snack
https://snack.expo.io/#asad_4561/b21f6d?session_id=snack-session-EGg1r5WPo&preview=true&platform=web&iframeId=g11cgnoglm&supportedPlatforms=ios,android,web&name=Fetch%20Example&description=Example%20usage&waitForData=true
Here is some good refs for your problem, by reading them your problems will be solved:
Medium: This is very good
RN docs
Another Good ref