Datastax Astra netlify 和 react-app,我应该使用 nodejs 客户端还是 REST API 来实现无服务器功能?

Datastax Astra netlify and react-app, should I use nodejs client or REST API for serverless functions?

我用“create-react-app”构建了一个简单的 React 应用程序,我想将无服务器功能与 netlify 结合使用。 为此,我使用 DataStax Astra Cassandra DB,并在我的 React 项目中创建了一个 netlify.toml 配置和 .env 变量(用于数据库)。

我为 netlify 设置了一个无服务器函数文件夹:

const { createClient } = require('@astrajs/collections')

// create an Astra client
exports.handler = async function (event, context) {
    try {
        const astraClient = await createClient({
            astraDatabaseId: process.env.ASTRA_DB_ID,
            astraDatabaseRegion: process.env.ASTRA_DB_REGION,
            applicationToken: process.env.ASTRA_DB_APPLICATION_TOKEN,
        })
        // const basePath = `/api/rest/v2/KEYSPACES/${process.env.ASTRA_DB_KEYSPACE}/collections/messages`

        const messagesCollection = astraClient
            .namespace(process.env.ASTRA_DB_KEYSPACE)
            .collection('messages')
    const message = await messagesCollection.create('msg1', {
        text: 'hello my name is Marc!',
    })
    return {
        statusCode: 200,
        body: JSON.stringify(message),
    }
} catch (e) {
    console.error(e)
    return {
        statusCode: 500,
        body: JSON.stringify(e),
    }
}

它在我 运行 netlify dev 时起作用,然后我的 .env 变量被注入到 .js 文件中。 但是,我想知道我是应该在这里使用 nodejs datastax 集合,还是应该使用 datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html) 中的 REST API 函数?因为有了 React,它本质上是在浏览器中 运行ning 还是不?我想知道为什么这仍然适用于 nodejs(因为它不是带有反应的 nodejs 环境,或者是吗?) 我正在通过 localhost:8888/.netlify/functions/functionName 访问我的功能,这是从 nodejs 服务器提供的还是浏览器的东西?

it works when I run netlify dev , then my .env variables are injected into the .js file. However, I am wondering if I should use the nodejs datastax collections here, or the REST API functions from datastax (https://docs.datastax.com/en/astra/docs/astra-collection-client.html)? Because with react, it's essentially running in the browser or not?

正确 - 如果您直接从您的 React 应用程序连接到您的数据库,您会将您的 Astra 凭据暴露给全世界。

I am wondering why this still works with nodejs (because its not a nodejs environment with react, or is it?) I am getting access to my functions via localhost:8888/.netlify/functions/functionName is this served from a nodejs server or is it browser stuff?

Netlify 函数 运行 服务器端,因此在您的函数代码中连接到 Astra 是安全的。这是一个例子:https://github.com/DataStax-Examples/todo-astra-jamstack-netlify/blob/master/functions/createTodo.js