2

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),
    };
  }
};

1 Answers1

3

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.