Firebase cloud function http request crashing - node.js

I'm trying to send expo push notification via firebase cloud functions, in order to send notifications from the web app to devices that have downloaded the mobile app.
When I send the request from Postman, it works just fine... i get the ok response and the notification shows up on my phone. But when I try to make the request from the web app, i get this in the functions log:
Function execution took 22 ms, finished with status: 'crash'
Any ideas why is this happening? Couldn't find anything to explain this so far.
Here's my function:
exports.reportNotification = functions.https.onRequest((request, response) => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(messages),
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(400).json({ error: err }));
});
My post request on Postman:
{
"expoPushToken": ["ExponentPushToken[xxx-xxxxxxxxxxxxx]"]
}
And I call the function with axios in the web app:
axios({
url: "reportNotification",
baseURL: functionsBaseURL,
method: "post",
data: {
expoPushToken: tokens,
},
})
I checked and the tokens on this request are in the same format that the one on Postman.
Thanks.

It was a cors problem, solved with this modification:
exports.reportNotification = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
axios.post("https://exp.host/--/api/v2/push/send", JSON.stringify(messages), {
headers: {
"Accept": "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(200).json({ error: err }));
});
});

Related

Unable to Fetch Response - 201 Message [duplicate]

This question already has answers here:
how to get data from response from fetch javascript request
(2 answers)
Closed 6 months ago.
I am trying to retrieve a response from an API using fetch in NextJS, I can get the message by calling the API but am unable to get anything using fetch. All I get from fetch is response 201 message that it's created.
When I run the API in postman I get the response:
{
"id": "21a1f0a6-f6c4-4aaf-9f48-2c9dba276646",
"status": "SUBMITTED"
}
But when I call the API using fetch in NestJS I get the response:
Response { type: "cors", url: "http://localhost:9000/api/v1/fireblocks/createTxnVaultToVault", redirected: false, status: 201, ok: true, statusText: "Created", headers: Headers, body: ReadableStream, bodyUsed: false }
Expected Behavior
The expected behavior is to get the same response as the API postman response. I need the tracking id to be passed into the UI
Backend - API Service & Controller Code in NestJS
Below is the API to run a transaction, it's coming from a NodeJS like framework (NestJS):
async createTxnVaultToVault(txn: Txn) {
this.logger.log("Creating transaction for account: " + txn);
this.logger.log("Transaction data: " + JSON.stringify(txn));
const payload: TransactionArguments = {
assetId: txn.asset,
source: {
type: PeerType.VAULT_ACCOUNT,
id: String(txn.source)
},
destination: {
type: PeerType.VAULT_ACCOUNT,
id: String(txn.dest)
},
amount: String(txn.amount),
fee: String(txn.fee),
note: txn.note
};
this.logger.log("TXN Payload data: " + JSON.stringify(payload));
return fireblocks().createTransaction(payload)
.then(res => res)
.then(res => {
console.log(res)
return res;
})
.catch(err => {
console.log(err);
return err;
});
}
Below is the controller to run a transactions, it's coming from a NodeJS like framework (NestJS):
#ApiTags('Fireblocks Transactions - Create Vault to Vault Transaction')
#Post('/createTxnVaultToVault')
async createTxnVaultToVault(
#Body() txn: Txn
): Promise<any> {
return this.appService.createTxnVaultToVault(txn)
.catch(e => {
this.logger.log(e);
return getError(e);
});
}
Frontend - Fetch Code in NextJS
export async function transferFunds(txn) {
const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault";
console.log(txn);
return fetch(req_url, {
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(txn)
})
.then(resp => {
console.log(resp);
})
.then(resp => {
console.log(resp);
return resp;
})
.catch(err => {
console.log(err);
});
}
It worked by changing how the UI received data. Below is how the API should be called:
Frontend - Fetch Code in NextJS
export async function transferFunds(txn) {
const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault";
console.log(txn);
return fetch(req_url, {
method: 'POST',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(txn)
})
.then( async resp => {
//console.log(await resp.json())
return await resp.json();
})
.then(data => {
console.log(data);
return data;
//return data;
});
}

Make Request With Node.JS To Change Vanity Discord

How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }
I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.

cypress error while testing file upload to api

I am testing an api which requires to send an image in the request body but I am getting error,
Here's my code:
it("should register a new litigant/customer", () => {
cy.fixture('testImg1.png', "base64").then(base64 => {
const blob = Cypress.Blob.base64StringToBlob(base64, 'image/png')
const bodyObj = {
email: "customer#customer.com",
password: "123456789",
profilePicture: blob
}
let formData = new FormData()
for (let key in bodyObj){
formData.append(key, bodyObj[key])
}
cy.request({
method: "POST",
url: endpoints.signup.litigant,
headers: { "content-type": "application/x-www-form-urlencoded" },
body: formData,
}).then(res => {
expect(...)
})
})
})
But I am getting this error:
Does anyone know how to fix this??

How to set message in express api and get that message in react native app

I am trying to send data to express api from react native, and when data is stored in mongodb return the message. i am trying to recieve the message in react native app.
I have tried these
1st Method
App.js
var inputData = {
"email": text,
"password": number
}
fetch('http://192.168.43.246:4000/api/addUser', {
method: 'POST',
body: JSON.stringify(inputData),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => console.log(response.text()))
Contoller.js
addNewUser: function(req, res) {
data = "User Registered Successfully..."
return res.send(data)
The response from this request is
Promise {
_U: 0,
_V: 0,
_W: null,
_X: null
}
_U: 0
_V: 1
_W: "User Registered Successfully..."
2st Method
App.js
var inputData = {
"email": text,
"password": number
}
fetch('http://192.168.43.246:4000/api/addUser', {
method: 'POST',
body: JSON.stringify(inputData),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => console.log(response))
Contoller.js
addNewUser: function(req, res) {
data = "User Registered Successfully..."
return res.send(data)
The response from this request is
Response {type: "default", status: 200, ok: true, statusText: "", headers: Headers, …}
bodyUsed: false
headers: Headers {map: {…}}
ok: true
status: 200
statusText: ""
type: "default"
url: "http://192.168.43.246:4000/api/addUser"
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}
__proto__: Object
How to recieve that message in react native that is sent from express api
You're really close to it. In the frontend part, response.text() return a promise, we need to add another then block to get the data
var inputData = {
"email": text,
"password": number
}
fetch('http://192.168.43.246:4000/api/addUser', {
method: 'POST',
body: JSON.stringify(inputData),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(response => response.text())
.then(data => console.log(data));
You can find more information about fetch method here

difficulty in getting authorization from dialogflow api v1. Getting error "Request failed with status code 401"

im using axios to connect my bot to dialog-flow API v1.it is returning a 401 error saying unauthorized?
i have all ready set up the headers and the data types to application/json.
var axios =require('axios');
var URL ='https://api.dialogflow.com/v1/';
let config = {
headers: {
"Authorization": "Bearer " + '4c52dfb9db61xxxxxxxxxxxxx',
"Content-Type": "application/json"
}
}
var bodyParameters = {
"queryInput": { "text":
{ }
},
"query": "hi hello",
"languageCode": "en",
"sessionId": "12345",
"timezone": "xxxxx"
};
axios.get(URL,bodyParameters, config)
.then(function(res){
console.log(res.data);
}).catch(function(error){
console.log(error);
});
is there some error in authorization?
after searching i found that it was much easy to do API request using node-fetch
fetch(URL+"query?v=20150910", {
body: JSON.stringify({query: "new york city", lang: "en", sessionId: "12345"}),
headers: {
'content-type': 'application/json',
"Authorization": "Bearer " + accessToken,
},
method: 'POST',
})
.then(response => response.json())
.then(data => {
console.log(data.result.fulfillment.speech);
return data.result.fulfillment.speech;
})
.catch(error => console.error(error))

Resources