【发布时间】:2022-12-18 15:10:11
【问题描述】:
我有一个 deno 新鲜样板应用程序,其中添加了一个名为 create 的视图。你登陆了一个简单(但丑陋)的表单视图,你通过输入电子邮件和密钥然后按submit创建了一个新用户。这是屏幕:
当我点击提交时,屏幕没有改变,但我在我的网络控制台中得到了这个。
更奇怪的是,当我检查我的数据库时,我有 6 个相同电子邮件和密钥的条目。我不知道为什么会这样。我只按了一次按钮:
几乎所有 create 页面逻辑发生的三个文件是 create.tsx、createUser.tsx 和 Creator.tsx
创建.tsx:
import Layout from '../components/layouts.tsx';
import Creator from "../islands/Creator.tsx"
export default function User(props: PageProps) {
return (
<Layout>
<Creator />
</Layout>
)
}
创建用户.tsx:
import { Handlers, PageProps } from "$fresh/server.ts";
import UserDb from "../../database.ts";
export const handler = {
POST: async (request, ctx) => {
const reqJsn = (await request.json());
const body = reqJsn;
const email = body.email;
const key = body.key;
console.log(email);
console.log(key);
if (!email || !key) {
ctx.status = 422;
ctx.body = { msg: "Incorrect user data. Email and key are required" };
return;
}
const userId = await UserDb.create({
email: email,
key: key,
created_at: new Date()
});
ctx.body = { msg: "User created", userId };
}
}
造物主.tsx:
// import { useState } from "preact/hooks";
import { useState, useEffect } from "preact/hooks";
import { Handlers, PageProps } from "$fresh/server.ts";
import UserDb from "../database.ts";
interface CreatorProps {
email: string,
key: string
}
export default function Creator(props: CreatorProps) {
async function handleSubmit(event) {
event.preventDefault();
const emailInput = event.target.email;
const ageInput = event.target.key;
console.log(emailInput.value);
console.log(ageInput.value);
const resp = await createNewUser(emailInput.value, ageInput.value);
return resp
};
async function createNewUser(email, key) {
const rawPosts = await fetch('http://localhost:8000/api/createUser', {
"method": "POST",
"headers": {
"content-type": "text/plain"
},
"body": JSON.stringify({
email: email,
key: key,
})
});
console.log(rawPosts);
}
return (
<div>
<h1 class="text rounded-lg p-4 my-8"> Search </h1>
<form method="post" onSubmit={async (e) => handleSubmit(e)}>
<input class="center rounded-lg p-4 my-8" id="email" name="email" />
<input class="center rounded-lg p-4 my-8" id="key" name="key" />
<br />
<button
class="px-5 py-2.5 text-sm font-medium bg-blue-600 rounded-md shadow disabled:(bg-gray-800 border border-blue-600 opacity-50 cursor-not-allowed)"
type="submit">Submit
</button>
</form>
<br />
{/* <ul>
{results.map((name) => <li key={name}>{name}</li>)}
</ul> */}
</div>
);
};
同样,我提供了一个最小的可重现示例。要运行它,您需要运行一个 postgres 实例,在项目的根目录中创建一个 .env 文件并添加您的 postgres 变量,如下所示:
环境:
POSTGRES_USER=postgresuserone
POSTGRES_PASSWORD=pass2woR3d
POSTGRES_DB=postgresdbone
转到 repo 的根目录并在你的终端中输入 deno task start 并且它可以工作。请记住导航至localhost:8000/create,填写 2 字段并按提交。现在您的数据库中将有 6 个条目。
【问题讨论】:
标签: forms request event-handling fetch deno