I have been working on a TikTok clone app. So I created my database with Astra DB and set up two functions inside a function folder to test out if my posts are working. I am using netlify dev to test out the applications. But when I redirect http://localhost:8888/.netlify/functions/addData
I get this failed get request error
Request from ::1: GET /.netlify/functions/addData
Error: Request Failed: [object Object]
Stack Trace: Request failed with status code 401
at axiosRequest (D:\tiktokclone\node_modules\#astrajs\rest\src\rest.js:126:11)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async AstraClient._request (D:\tiktokclone\node_modules\#astrajs\rest\src\rest.js:199:22)
at async AstraClient.put (D:\tiktokclone\node_modules\#astrajs\rest\src\rest.js:263:12)
at async AstraCollection._put (D:\tiktokclone\node_modules\#astrajs\collections\src\collections.js:69:22)
at async Object.exports.handler (D:\tiktokclone\functions\addData.js:17:9)
Response with status 500 in 231 ms.
I quite don't understand what causes this. All the credentials inside my .env folder were correct.Here is the code I used to make the request
const { createClient } = require("#astrajs/collections");
const collection = "posts";
exports.handler = async function (event, context, callback) {
const astraClient = await createClient({
astraDatabaseId: process.env.ASTRA_DB_ID,
astraDatabaseRegion: process.env.ASTRA_DB_REGION,
applicationToken: process.env.ASTRA_DB_APPLICATION_TOKEN,
});
console.log(astraClient)
console.log(collection)
console.log('Hello')
const posts = astraClient
.namespace(process.env.ASTRA_DB_KEYSPACE)
.collection(collection);
try {
await posts.create("a post", {
title: "my first post",
});
return {
statusCode: 200,
};
} catch (e) {
console.error(e);
return {
statusCode: 500,
body: JSON.stringify(e),
};
}
};
I found a fix. For some reason, I was trying to call the API using an application token and it was giving me the 401 error. When I used username and password it worked.
const astraClient = await createClient({
astraDatabaseId: process.env.ASTRA_DB_ID,
astraDatabaseRegion: process.env.ASTRA_DB_REGION,
username: process.env.ASTRA_DB_USERNAME,
password: process.env.ASTRA_DB_PASSWORD,
});
username is the client ID and password is the client secret. This error happened because of a slight confusion with the REST API and the Document API. Astra DB uses application token for authenticating document API while REST API uses client ID and Password.
Related
Some context
I've created a service worker to send notifications to registered users.
It works well until I tried to implement a sort of id to each people who register to a service worker (to send notification).
I do that because I have to delete old registration from my database, so I took the choice to let each users three registration (one for mobile device and two others for different navigator on computer) and if there is more, I want to remove from the database the older.
Tools
I'm using nodejs, express and mySql for the database.
The issue
When I launch a subscription I got this error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
I saw in an other post that it's because they try to JSON.parse what's already an object.
But in my case, I can't find where I parse, see the part which are concerned:
// service.js (service worker file)
// saveSubscription saves the subscription to the backend
const saveSubscription = async (subscription, usrCode) => {
const SERVER_URL = 'https://mywebsite:4000/save-subscription'
subscription = JSON.stringify(subscription);
console.log(subscription); // I got here what I expect
console.log(usrCode); // <-------------------------------- HERE I GOT UNDEFIND
const response = await fetch(SERVER_URL, {
method: 'post',
headers: {
'Content-Type' : 'application/json',
},
body : {
subscription: subscription,
usrCode: usrCode
}
})
return response
}
But when I console.log(usrCode) in my inspector, I got the good value.
So how should I do to get the value in service.js
Maybe the problem is from:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
At the beginning I thought that the issue is from the back (because I'm not really good with async function).
And here is the back, If maybe I got something wrong.
// index.js (backend)
// Insert into database
const saveToDatabase = async (subscription, usrCode) => {
// make to connection to the database.
pool.getConnection(function (err, connection) {
if (err) throw err; // not connected!
console.log(usrCode);
console.log(subscription);
connection.query(`INSERT INTO webpushsub (webpushsub_info, webpushsub_code) VALUES ('${subscription}', '${usrCode}')`, function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
console.log(result);
connection.release();
});
});
}
// The new /save-subscription endpoint
app.post('/save-subscription', async (req, res) => {
const usrCode = req.body.usrCode; // <------------------ I'm not sure about this part
const subscription = req.body.subscription
await saveToDatabase(JSON.stringify(subscription, usrCode)) //Method to save the subscription to Database
res.json({ message: 'success' })
})
By searching on google, I've found this tutorial. So the reason why usrCode is undefined is because the service worker doesn't have access to a data stored in front.
First you have to pass it in the URL as following:
// swinstaller.js (front)
// SERVICE WORKER INITIALIZATION
const registerServiceWorker = async (usrCode) => {
const swRegistration = await navigator.serviceWorker.register('service.js?config=' + usrCode); //notice the file name
return swRegistration;
}
And then get it in the service worker:
// service.js (service worker file)
// get the usrCode
const usrCode = new URL(location).searchParams.get('config');
const googleLogin = useGoogleLogin({.
flow: 'auth-code',
onSuccess: async (codeResponse) => {
const response = await axios.post(
'my backend api '
{
accessToken: codeResponse.code,
oAuthAgency: 2,
}
);
console.log(codeResponse);
},
onError: (errorResponse) => console.log(errorResponse),
});
This is React Oauth2 grammar. I want to do by authorization code flow
sending authorization code to backend for getting access token.
I'm working on this for two days. Please help me.
I have set up payments with stripe using Netlify function by following this article https://www.netlify.com/blog/2020/04/22/automate-order-fulfillment-w/stripe-webhooks-netlify-functions/ and in my Stripe dashboard I get error saying that:
Webhook Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
Now I am not sure if the user gets confirmation email, Sendgrid does not show any activity, however it has not shown any when I was testing this flow previously, and although I received confirmation email. Unfortunately back then I pressed resend by my webhook activity details in Stripe dashboard, and I am not sure if I should be resending those or do they go through. Would anyone be able to tell me what is wrong with my code?
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
exports.handler = async ({ body, headers }) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
body,
headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET
);
if (stripeEvent.type === "charge.succeeded") {
const emailTo = stripeEvent.data.object.billing_details.email;
const msg = {
to: emailTo,
from: process.env.FROM_EMAIL_ADDRESS,
subject: `Thanks!`,
html: `elox`,
};
await sgMail.send(msg);
}
return {
statusCode: 200,
body: JSON.stringify({ received: true }),
};
} catch (err) {
console.log(`Stripe webhook failed with ${err}`);
return {
statusCode: 400,
body: `Webhook Error: ${err.message}`,
};
}
};
Thanks!
I got the same issue.
Locally with the stripes-cli everything works fine.
It seems that the lambda didn't hand over the raw body to the stripes.webhook.constructEvent.
Therefore my solution was to change the method signature to the following and use the event.body object.
exports.handler = async(event, context ) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
event.body,
event.headers['stripe-signature'],
endpointSecret
);....
I am trying to connect the AWS Lambda with SQL query to an AWS RDS (MySQL) using the Data API and return the query result for a user with a particular id.
This is how the handler looks like:
'use strict';
const AWS = require('aws-sdk')
const RDS = new AWS.RDSDataService({ endpoint: '******.cluster-*********.us-west-2.rds.amazonaws.com' })
module.exports.fetchById = async (event, context, callback) => {
const req_id = event.pathParameters.id;
try {
const params = {
resourceArn: 'arn:aws:rds:us-west-2:***********',
secretArn: 'arn:aws:secretsmanager********',
sql: `SELECT * FROM user WHERE user_id = :id`,
database: '*********',
includeResultMetadata: true,
parameters: [
{ id: req_id },
]
}
const db_res = await rdsDataService.executeStatement(params).promise();
const response = {
body: JSON.stringify({
message: 'Data fetched!!',
data: db_res.records
})
};
callback(null, response);
} catch (error) {
console.log('Error Received', error)
}
};
serverless.yml
functions:
fetchByIdId:
handler: handler.fetchById
events:
- http:
path: user/{id}
method: get
authorizer:
name: cognito-authorizer
arn: arn:aws:***********
request:
parameters:
paths:
id: true
Few issues that I need to work upon:
If I instantiate like:
const RDS = new AWS.RDSDataService({ endpoint: '******.cluster-*********.us-west-2.rds.amazonaws.com' })
by including an endpoint cluster as a parameter, the handler function does not execute at all. It just keeps throwing:
{"errorMessage": "2020-10-30T07:31:12.258Z c4b4ca2d-3cbb-4733-8cfe-0c7aad228c29 Task timed out after 6.01 seconds"}.
Tried increasing the timeout also but it didn't made any difference & the error still perists.
But if endpoint is removed & only used like:
const RDS = new AWS.RDSDataService()
, the function does not throw timeout error, but these two new issues are faced:
The id is required. I passed the required config to the yml file, but it
doesn't seem to mark it as required. If the http endpoint is executed as
/user/, it does not throw any error.
I need to perform input data validation/sanitization for the request
parameters. On executing the endpoint /user/123, it throws an error:
INFO Error Received UnexpectedParameter: Unexpected key 'id' found in params.parameters[0].
I read out in the documentation but could not find any particular clue to complete the same.
Any help to resolve this is appreciated.
I have a simple server which accepts POST requests and responds with the 413 Request entity too large error if the request body exceeds allowed size. When I'm testing it using Jest the request sometimes returns correct error, but more often it returns { code: EPIPE, syscall: write } error.
I tested server using cURL and from node javascript file and the server worked as expected, but Jest testing still gives me that error. I also tried another request libraries, they gave the same error.
beforeAll(() => {
server.listen(testingPort);
});
afterAll(() => {
server.close();
});
describe("POST request", () => {
test("should return error 413 in respense to exceeded file size", async () => {
const fileContent = new Array(1024 * 1024 + 10).join("*");
const fileName = "post-test-file.txt";
const urlObj = new URL(fileName, host);
try {
await axios.post(urlObj.href, fileContent);
} catch (e) {
console.log(e.code, e.errno, e.syscall); // EPIPE EPIPE write
// expect(e.response.status).toBe(413);
}
});
Maybe you have any thoughts about this?
It seems that the issue is very old and not quite resolved:
https://github.com/nodejs/node/issues/947
For me the workaround is using a stream.