(1/9/2023(更新:SvlteKit现在支持仅服务器加载功能和向服务器发送请求的Form操作。
我想调用我的数据库,但我不希望最终用户访问我设置的API端点。我想知道如何从lib文件夹中的一个文件调用我的数据库,并在那里返回数据。当我尝试它时,我得到错误global not defined
:
lib/db.js:
import dotenv from "dotenv";
dotenv.config();
import { MongoClient } from "mongodb";
const uri = process.env["MONGODB_URI"];
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
};
let client;
let clientPromise;
if (!uri) {
throw new Error("Please add your Mongo URI to .env.local");
}
if (process.env["NODE_ENV"] === "development") {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;
路线/项目/index.js:
import clientPromise from "$lib/db";
export async function get() {
const client = await clientPromise;
const db = client.db();
const data = await db.collection("items").find({}).toArray();
const items = data.map(({ name }) => ({ name }));
if (items) {
return {
body: {
items,
},
};
}
}
我的尝试:lib/stores/items.js
import clientPromise from "$lib/db";
import { writable } from "svelte/store";
export const items= writable([]);
const fetchItems = async () => {
const client = await clientPromise;
const db = client.db();
const data = await db.collection("items").find({}).toArray();
const items = data.map(({ name }) => ({ name }));
substances.set(items);
};
fetchItems();
在不同的地方尝试上面的代码总是会在客户端中产生global not defined
错误。
我从有同样问题的人那里找到了一个问题,但我不知道如何创建帮助文件。
保护API是在后端完成的。通常它要么是服务器(如NodeJS(,要么是工具Nginx/Apache(代理等(。你基本上是在寻找内容安全策略主题,它是虚幻的,但与SveltKit无关。
顺便说一句,直接从前端调用DB是不安全的,也是不可能的。
要从任何数据库获取数据,您应该创建enpoint
对于用户身份验证,您可以创建handle
挂钩:
export async function handle({ request, resolve }) {
let user = await authenticate(request)
request.locals.user = user
request.locals.isAuthenticated = !!user
if (request.path.startsWith('/api')) {
if (!user) {
return {
status: 401,
body: JSON.stringify({
error: {
message: 'Unauthorized'
}
})
}
}
const response = await resolve(request)
return response
}