node JS如何与VueJs通信(appwrite SDK问题)

How can node JS communicate with VueJs (appwrite SDK Question)

我正在尝试在 appwrite 应用程序中使用户配置文件动态化。我希望所有用户都可以访问每个用户个人资料页面,所以它是这样的 (www.appname.com/users/{userid})。

我是 node JS 的新手,但我设法为 node 安装了 appwrite SDK 并为 node 创建了一个单独的文件夹,当我 运行 node 中的以下代码时,它让我获得了预期的用户终端。

const sdk = require("node-appwrite");

// Init SDK
let client = new sdk.Client();

let users = new sdk.Users(client);

client
  .setEndpoint("http://localhost/v1") // Your API Endpoint
  .setProject("myProjectId") // Your project ID
  .setKey(
    "mykey"
  ); // Your secret API key

let promise = users.get("myUserId");

promise.then(
  function (response) {
    console.log(response);
  },
  function (error) {
    console.log(error);
  }
);

但是我希望能够用Vuejs来调出这个结果!我希望能够使用 Vue 组件中的 (users.get)。我怎样才能做到这一点?

这是我到目前为止尝试过的方法: 我创建了 UserService.js 文件并添加了以下函数以从节点 Js

中获取 users.get

import users from "../../../api/server";

export async function getUser(userId) {
  let promise = users.get(userId);

  promise.then(
    function (response) {
      console.log(response);
    },
    function (error) {
      console.log(error);
    }
  );
}

我从我的 VueJS 组件中调用它

<script>
import { getUser } from "../../services/UserService";
export default {
  name: "Profile",
  props: ["id"],
  data() {
    return {
      userprfile: false,
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    getUser() {
      getUser(this.id).then((response) => {
        console.log(response);
      });
    },
  },
};
</script>

但是不行

我想要的只是一种允许我在我的 vueJS 组件中使用 appwrite nodeJS SDK 的方法。我需要能够将用户 ID 传递给它并取回 VueJS 组件中的用户


更新:

下面的代码有效,我现在可以从 appwrite NodeJS SDK 检索数据到我的浏览器,但问题是我希望它是动态的。我需要一种方法将 UserID 从 vue 传递到 NodeJS sdk 并检索数据。

const express = require("express");
const path = require("path");
const app = express(),
  bodyParser = require("body-parser");
port = 3080;

// place holder for the data

const sdk = require("node-appwrite");

// Init SDK
let client = new sdk.Client();

let users = new sdk.Users(client);

client
  .setEndpoint("http://localhost/v1") // Your API Endpoint
  .setProject("myProjectID") // Your project ID
  .setKey(
    "MySecretApiKey"
  ); // Your secret API key


app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "../appwrite-app/build")));

app.get("/v1/users", (req, res) => {
  console.log("api/users called!");
  let promise = users.get("userId");
  promise.then(
    function (response) {
      res.json(response);
    },
    function (error) {
      console.log(error);
    }
  );
});

app.listen(port, () => {
  console.log(`Server listening on the port::${port}`);
});

您似乎正尝试在客户端(浏览器)上使用仅节点模块。您不能在使用本机节点模块的客户端上使用任何模块 - 在这种情况下 fs.

因此,您需要从前端应用程序向服务器应用程序发送请求 (API)。在 API 上执行任何文件 system/database 检索,然后将结果发送回客户端。

将 backend/frontend 作为单独的应用程序编写是很常见的 - 在单独的文件夹中,甚至存储在单独的存储库中。

您也不应在客户端公开任何密钥。

'client' 一词也可能存在一些混淆。大多数时候,它用于在 Web 浏览器中引用应用程序 运行,但您还可以获得节点 sdk,它们是它们使用的服务的 'clients' - 就像您的情况下的 node-appwrite。