我想尝试一下 Vercel 最近添加的这些新存储功能,但无法让 Postgress 工作。我使用了这个模板。它部署得非常好,但是当我尝试在本地运行它时,我不知道该怎么做。这就是我到目前为止所做的:
npm i
现在我得到了包含所有静态内容的页面,但没有来自数据库的数据。当我访问 localhost:3000/api/get-users 时,我收到以下消息:
"VercelPostgresError - 'missing_connection_string': You did not supply a 'connectionString' and no 'POSTGRES_URL' env var was found."
这就是
get-users.ts
的样子:
import { createPool, sql } from '@vercel/postgres';
async function seed() {
const createTable = await sql`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
image VARCHAR(255),
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
`;
console.log(`Created "users" table`);
const users = await Promise.all([
sql`
INSERT INTO users (name, email, image)
VALUES ('Guillermo Rauch', '[email protected]', 'https://pbs.twimg.com/profile_images/1576257734810312704/ucxb4lHy_400x400.jpg')
ON CONFLICT (email) DO NOTHING;
`,
sql`
INSERT INTO users (name, email, image)
VALUES ('Lee Robinson', '[email protected]', 'https://pbs.twimg.com/profile_images/1587647097670467584/adWRdqQ6_400x400.jpg')
ON CONFLICT (email) DO NOTHING;
`,
sql`
INSERT INTO users (name, email, image)
VALUES ('Steven Tey', '[email protected]', 'https://pbs.twimg.com/profile_images/1506792347840888834/dS-r50Je_400x400.jpg')
ON CONFLICT (email) DO NOTHING;
`,
]);
console.log(`Seeded ${users.length} users`);
return {
createTable,
users,
};
}
export default defineEventHandler(async () => {
const startTime = Date.now();
const db = createPool();
try {
const { rows: users } = await db.query('SELECT * FROM users');
const duration = Date.now() - startTime;
return {
users: users,
duration: duration
};
} catch (error) {
// @ts-ignore
if (error?.message === `relation "users" does not exist`) {
console.log(
"Table does not exist, creating and seeding it with dummy data now..."
);
// Table is not created yet
await seed();
const { rows: users } = await db.query('SELECT * FROM users');
const duration = Date.now() - startTime;
return {
users: users,
duration: duration
};
} else {
throw error;
}
}
});
我尝试解决这个问题:
Vercel 在其网站上提供了一些快速入门代码片段,其中之一是:
import pg from 'pg';
const { Pool } = pg;
const pool = new Pool({
connectionString: process.env.POSTGRES_URL + "?sslmode=require",
})
所以我想我可以在我的代码中做这样的事情:
const db = createPool({
connectionString: process.env.POSTGRES_URL + "?sslmode=require",
});
这会显示以下消息:
"VercelPostgresError - 'invalid_connection_string': This connection string is meant to be used with a direct connection. Make sure to use a pooled connection string or try createClient() instead."
不知道这意味着什么。他们有一些关于这些错误的文档,但他们没有帮助我。另外,这个快速入门指南根本没有帮助我。 这里有人可以帮助我吗?
.env
而不是
.env.local
就可以了。我不知道是什么或为什么:)
process.env.POSTGRES_URL
不适用于Vite,后者
需要在变量前面加上
VITE_
才能访问它们。@vercel/postgres 推荐使用 dotenv-expand
vite.config.js 中启用环境变量使用 svelte-kit 导入连接网址:
import { POSTGRES_URL } from '$env/static/private'