I am running an angular app using here maps api-keys for authentication. But I'm getting {status: 401, message: "Invalid app_id app_code combination"} when I'm not using app_id nor app_code at all.
This error occurs when I use the search api. Below is an example of how my search works:
public places(query: string) {
this.map.removeObjects(this.map.getObjects());
this.search.request({ "q": query, "at": this.lat + "," + this.lng }, {}, data => {
for (let i = 0; i < data.results.items.length; i++) {
this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);
if (i == 0)
this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })
}
},
error => {
console.error("hello"+ error);
});
}
Related
UPDATE
It seems that I can't get the bucket's reference correctly or use the bucket functions.
When I do
// Get the photos' bucket
const bucket = gcs.bucket("photos");
console.log("deleting the bucket");
// Delete bucket
bucket.delete();
I get the error too (but the bucket exists in my project)
Error: There is an account problem for the requested project.
at new ApiError (/workspace/node_modules/#google-cloud/common/build/src/util.js:58:15)
at Util.parseHttpRespBody (/workspace/node_modules/#google-cloud/common/build/src/util.js:193:38)
at Util.handleResp (/workspace/node_modules/#google-cloud/common/build/src/util.js:134:117)
at retryRequest (/workspace/node_modules/#google-cloud/common/build/src/util.js:432:22)
at onResponse (/workspace/node_modules/retry-request/index.js:206:7)
at /workspace/node_modules/teeny-request/build/src/index.js:233:13
at process._tickCallback (internal/process/next_tick.js:68:7)
PROBLEM
I am having this error:
{
"error": {
"code": 401,
"message": "There is an account problem for the requested project.",
"errors": [
{
"message": "There is an account problem for the requested project.",
"domain": "global",
"reason": "required",
"locationType": "header",
"location": "Authorization"
}
]
}
}
PassThrough {
Unhandled error { Error: There is an account problem for the requested project
at new ApiError (/workspace/node_modules/#google-cloud/common/build/src/util.js:58:15)
_readableState:
ReadableState {
at Util.parseHttpRespBody (/workspace/node_modules/#google-cloud/common/build/src/util.js:193:38)
...
What I am doing is just:
Get a bucket reference
Get a file from the bucket with the file's path
Get metadata and the signed url of the file.
My problem is the third step. When I call those functions, I don't receive any answer... no metadata, no url.
Here is the code:
const { Storage } = require("#google-cloud/storage");
const gsc = new Storage()
const serviceAccount = require("./serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://my_app_id.firebaseio.com",
storageBucket: "my_app_id.appspot.com",
});
exports.validateImageDimensions = functions
.region("us-central1")
// Increased memory, decreased timeout (compared to defaults)
.runWith({ memory: "2GB", timeoutSeconds: 120 })
.https.onCall(async (data, context) => {
// Get the image's owner
const owner = context.auth.token.uid;
// Get the image's info
const { id, description, location, tags, time } = data;
// Get the photos' bucket
const bucket = gcs.bucket("photos");
// Get the file's path
const filePath = bucket.name + "/" + id;
// Get the file
const file = bucket.file(filePath);
console.log(JSON.stringify(file));
// Check if the file is a jpeg image
const metadata = await file.getMetadata(); // <------- ERROR
console.log(JSON.stringify(metadata));
const isJpgImage = metadata[0].contentType === "image/jpeg";
console.log(`Is jpeg? ${isJpgImage}`);
// Get the file's signed urls
const signedUrls = await file.getSignedUrl({
action: "read",
expires: "01-01-2100",
});
// signedUrls[0] contains the file's public URL
const publicUrl = signedUrls[0];
console.log(`publicUrl ${publicUrl}`);
console.log(`Url: ${publicUrl}`);
The file exists in my storage... and when I console.log it I can see:
{
"_eventsCount": 0,
"_events": {},
"id": "photos%2Fecbb4a5a-aa11-451f-b8af-efd3e8464a59",
"baseUrl": "/o",
"metadata": {},
"acl": { "pathPrefix": "/acl", "owners": {}, "readers": {}, "writers": {} },
"methods": {
"exists": { "reqOpts": { "qs": {} } },
"get": { "reqOpts": { "qs": {} } },
"delete": { "reqOpts": { "qs": {} } },
"getMetadata": { "reqOpts": { "qs": {} } },
"setMetadata": { "reqOpts": { "qs": {} } }
},
"bucket": {
"_eventsCount": 0,
"baseUrl": "/b",
"storage": {
"baseUrl": "https://storage.googleapis.com/storage/v1",
"projectId": "{{projectId}}",
"authClient": {
"cachedCredential": null,
"scopes": [
"https://www.googleapis.com/auth/iam",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/devstorage.full_control"
],
"jsonContent": null,
"_cachedProjectId": null
},
"globalInterceptors": [],
"acl": {
"OWNER_ROLE": "OWNER",
"READER_ROLE": "READER",
"WRITER_ROLE": "WRITER"
},
...
Any ideas? I have been googling for hours but no answer.
Also, my storage rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
function isSignedIn() {
return request.auth.uid != null;
}
match /photos/{photo} {
function hasValidSize() {
// Max. photo size = 30MB (For all dimensions)
return request.resource.size < 30 * 1024 * 1024;
}
function isImage() {
return request.resource.contentType.matches("image/.*");
}
allow read: if true;
allow write: if isSignedIn() && isImage() && hasValidSize();
}
}
}
What I'm trying to do:
Generate invoice using a third party lib.
Download/View invoice
My code
let createPdf = functions.https.onRequest(async (request, response) => {
// more code here
if (download == 'true') {
return response.status(200).download(__dirname + "/docs/" + newFileName, newFileName, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("Downloaded:", filename)
}
})
} else {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
return response.status(200).sendFile("/docs/" + newFileName, options, (err) => {
if (err) {
console.log(err);
} else {
console.log('Sent:', filename);
}
});
}
});
The error
{
"error": {
"code": 500,
"status": "INTERNAL",
"message": "function crashed",
"errors": [
"socket hang up"
]
}
}
Note:
When I return a simple string instead of the file it works.
Use express request and response objects to send a file.
Read this documentation: using_express_request_and_response_objects
And don't forget to use absolute path when using sendFile
I'm following the facebook messenger develop QuickStart to create a Node.js project, and I improved it to work in quick reply. Then when I tried the Generic Template and List Template, but it didn't work.
As the following source code, when I input the work "generic" or "list", the messenger should reply me with the template messege. But there was nothing happened.
} else if (received_message.text === 'generic') {
console.log('generic in');
response = {
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome!",
"image_url":"http://webapplication120181023051009.azurewebsites.net/colorcar1.jpg",
"subtitle":"We have the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://www.taobao.com/",
"messenger_extensions": false,
"webview_height_ratio": "tall",
"fallback_url": "https://www.taobao.com/"
},
"buttons":[
{
"type":"web_url",
"url":"https://www.taobao.com/",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}
}
// Sends the response message
callSendAPI(sender_psid, response);
// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
console.log('PAGE_ACCESS_TOKEN:');
console.log(PAGE_ACCESS_TOKEN);
console.log('request body:');
console.log(request_body);
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages?access_token=" + PAGE_ACCESS_TOKEN,
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
Sorry, I forgot to add the url into whiltelist.
I'm trying to send push notifications (at 12 PM the next day) to installations whose "updatedAt" field is not older than two days. Here's the code:
var two_days_ago_date = new Date()
two_days_ago_date.setDate(two_days_ago_date.getDate() - 2)
var push_time = new Date()
push_time.setDate(push_time.getDate() + 1)
push_time.setHours(12)
push_time.setMinutes(00)
push_time = push_time.toISOString()
push_time = push_time.substring(0, push_time.length - 1)
Parse.Cloud.httpRequest({
method: "POST",
headers: {
"X-Parse-Application-Id": "XXX",
"X-Parse-REST-API-Key": "XXX",
"Content-Type": "application/json"
},
body: {
"where":{
"appVersion":"1.4",
"updatedAt" : {"$gte" : two_days_ago_date}
},
"push_time": push_time,
"data": {
"alert":"",
"sound": ""
}
},
url: "https://api.parse.com/1/push"
}).then(function() {
console.log("Successful push");
}, function(error) {
console.log(error);
})
If I remove the restriction the code works fine, otherwise not.
I am using futures to make an async call to balanced payments. I want to catch errors and feed them back to the user so I can tell them why their payment failed.
Here is what I get on the server console. How can I parse out the errors[0].status, or errors[0].category_code from this error? I've tried to simply console.log(error[0].status);, but this does nothing.
I20140616-14:38:59.169(0)? "errors": [
I20140616-14:38:59.169(0)? {
I20140616-14:38:59.170(0)? "status": "Conflict",
I20140616-14:38:59.170(0)? "category_code": "card-not-validated",
I20140616-14:38:59.170(0)? "additional": null,
I20140616-14:38:59.170(0)? "status_code": 409,
I20140616-14:38:59.171(0)? "category_type": "logical",
I20140616-14:38:59.171(0)? "extras": {},
I20140616-14:38:59.171(0)? "request_id": "OHMf39d5030f56311e39cde02a
1fe53e539",
I20140616-14:38:59.171(0)? "description": "Card cannot be validated.
Your request id is OHMf39d5030f56311e39cde02a1fe53e539."
I20140616-14:38:59.172(0)? }
I20140616-14:38:59.172(0)? ]
Here is the future function I'm using.
var Future = Npm.require("fibers/future");
function extractFromPromise(promise) {
var fut = new Future();
promise.then(function (result) {
fut["return"](result);
}, function (error) {
fut["throw"](error);
fut.return(error.message);
});
return fut.wait();
}
I call this function from my code using something like this.
var customerData = extractFromPromise(balanced.marketplace.customers.create({
'name': customerInfo.fname + " " + customerInfo.lname,
"address": {
"city": customerInfo.city,
"state": customerInfo.region,
"line1": customerInfo.address_line1,
"line2": customerInfo.address_line2,
"postal_code": customerInfo.postal_code,
},
'email': customerInfo.email_address,
'phone': customerInfo.phone_number
}));
I had some help and got the answer. Hope this helps others. Here is the rewrite of the code I initially wrote.
The future code was both returning and throwing the error, so that was removed, the code was cleaned up a bit as well.
var Future = Npm.require("fibers/future");
function extractFromPromise(promise) {
var fut = new Future();
promise.then(function (result) {
fut.return(result);
}, function (error) {
console.log(error);
fut.throw(error);
});
return fut.wait();
}
And then the whole thing is wrapped in a try catch. I console log out the different parts of the message. Turned out that the JSON was stringified, so that had to be parsed first, then I could access the error like normal JSON data. And I've just learned that no errors will get back to the client unless you use the Meteor.error syntax first.
var customerData;
try {
customerData = extractFromPromise(balanced.marketplace.customers.create({
'name': customerInfo.fname + " " + customerInfo.lname,
"address": {
"city": customerInfo.city,
"state": customerInfo.region,
"line1": customerInfo.address_line1,
"line2": customerInfo.address_line2,
"postal_code": customerInfo.postal_code,
},
'email': customerInfo.email_address,
'phone': customerInfo.phone_number
}));
} catch (e) {
console.log(JSON.parse(e.message).errors[0].extras);
console.log(JSON.parse(e.message).errors[0].category_code);
var error = JSON.parse(e.message).errors[0];
throw new Meteor.Error(error.category_code, error.status_code, error.description, error.extras);
}