@none help
Unanswered
Sokoke posted this in #help-forum
SokokeOP
try {
const res = await fetch("/api/register", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
if (res.ok) {
setTouched({});
setState(initState);
await signIn();
toast.success("Successfully Created Account!");
return undefined;
} else {
const errorCode = res.status;
const errorResponse = await res.json();
if (errorCode === 500 || errorCode === 409) {
setError("Email is in use!");
toast.error("Email is in use!");
setState((prev) => ({
...prev,
isLoading: false,
}));
} else {
setError(errorResponse?.error);
toast.error(errorResponse?.error);
setState((prev) => ({
...prev,
isLoading: false,
}));
}
}
} catch (error: any) {
setState((prev) => ({
...prev,
isLoading: false,
error: error.message,
}));
setError(error?.message);
toast.error(error?.message);
}
}; here is the essential form submit code64 Replies
SokokeOP
@Finnish Spitz
Oops I left some stuff out
const onSubmit = async () => {
setState((prev) => ({
...prev,
isLoading: true,
}));
try {
const res = await fetch("/api/register", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
if (res.ok) {
setTouched({});
setState(initState);
await signIn();
toast.success("Successfully Created Account!");
return undefined;
} else {
const errorCode = res.status;
const errorResponse = await res.json();
if (errorCode === 500 || errorCode === 409) {
setError("Email is in use!");
toast.error("Email is in use!");
setState((prev) => ({
...prev,
isLoading: false,
}));
} else {
setError(errorResponse?.error);
toast.error(errorResponse?.error);
setState((prev) => ({
...prev,
isLoading: false,
}));
}
}
} catch (error: any) {
setState((prev) => ({
...prev,
isLoading: false,
error: error.message,
}));
setError(error?.message);
toast.error(error?.message);
}
};@Finnish Spitz
take note of this here
as you can see it defines the POST method to /api/register, and as I've already shown in the /api/register it takes a POST http method
take note of this here
const res = await fetch("/api/register", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
as you can see it defines the POST method to /api/register, and as I've already shown in the /api/register it takes a POST http method
export async function POST(req: Request) { This is App directory specific though, the one your usingFinnish Spitz
okeay look at this
const registerPage = () => {
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const router = useRouter();
const handleFormSubmit = async (e) => {
e.preventDefault();
const res = await fetch("/api/register", {
method: "POST",
body: JSON.stringify({email,password}),
headers: {
"Content-Type": "application/json",
},
});
};check my register function when submit
eh btw how to colorize code like yours?
SokokeOP
do
(typescript)
(code here)Idk how do explain it
Finnish Spitz
mine is not colorize
is it ok? i worry if you hard to see my code without colorize
SokokeOP
na its all good. Looking at your code I can't see why it wouldn't work.
You just need to modify the /api/register/route.js file so that it works properly with the app directory api handling
SokokeOP
Whats the problem?
Finnish Spitz
ohh i know, so i can not directly go to api/register because by default i am using GET method ,is not?
SokokeOP
Sort of, you cannot visit /api/register because you are accessing it through your browser. If your were to access it using a http method then you would be able to return email, password.
The other reason you cannot access /api/register is because you are using the app directory and looking at the code for the api, it is similar to that of a pages directory api
The other reason you cannot access /api/register is because you are using the app directory and looking at the code for the api, it is similar to that of a pages directory api
do you understand?
Finnish Spitz
yah, but my big problem is not
this is my code in api/register/route.js
export async function POST(req,res) {
try {
console.log("Isi req.body : ", req.body);
const { user } = req.body;
const saveUser = await prisma.User.create({
data: user,
});
res.status(201).json(saveUser);
} catch (error) {
res.status(400).json({ message: " Something went wrong" });
}
}and this submitHandler
const handleFormSubmit = async (e) => {
e.preventDefault();
const res = await fetch("/api/register", {
method: "POST",
body: JSON.stringify({email,password}),
headers: {
"Content-Type": "application/json",
},
});
console.log(res)
};SokokeOP
I'm pretty sure you need to destructure the request body and then create the prisma user using the email and password.
Just keep in mind though storing a password in plaintext is BAD
Just keep in mind though storing a password in plaintext is BAD
Finnish Spitz
there is a error
@Finnish Spitz there is a error
SokokeOP
That would mean the /api/register has errors.
You need to return a next response using
import { NextResponse } from 'next/server'
import { NextResponse } from 'next/server'
@Finnish Spitz this is my code in api/register/route.js
export async function POST(req,res) {
try {
console.log("Isi req.body : ", req.body);
const { user } = req.body;
const saveUser = await prisma.User.create({
data: user,
});
res.status(201).json(saveUser);
} catch (error) {
res.status(400).json({ message: " Something went wrong" });
}
}
problems:
* it is not (req, res) like in pages/api, just req
* request is no longer the express request, but the native
* not
* not
* it is not (req, res) like in pages/api, just req
* request is no longer the express request, but the native
Request* not
req.body but await req.json()* not
res.status, but new Response(...)basically you are writing pages/api code in route handlers which is not allowed. https://nextjs.org/docs/app/building-your-application/routing/router-handlers follow the documentation to see how to make actual route handlers
Finnish Spitz
btw, can i console log something in register/route.js
?
how to check is it working?
export async function POST(request) {
try {
console.log("Isi req.body : ", request.json());
const res = request.json()
return NextResponse.json(res)
} catch (error) {
// res.status(400).json({ message: " Something went wrong" });
}
}SokokeOP
It wont work. the POST() function needs to be POST(req: Request) as per the nextjs app directory api routing
and then the request.json will be req.json()
@Finnish Spitz how to check is it working?
export async function POST(request) {
try {
console.log("Isi req.body : ", request.json());
const res = request.json()
return NextResponse.json(res)
} catch (error) {
// res.status(400).json({ message: " Something went wrong" });
}
}
This doesn’t work because .json() returns a promise. Add await before request.json()
Also you can only run await request.json() once
@Sokoke It wont work. the POST() function needs to be POST(req: Request) as per the nextjs app directory api routing
Finnish Spitz
even i am not using typescipt? is Request is imported from outide?
SokokeOP
ah shit my bad u aint using typescript
Finnish Spitz
import { NextResponse } from 'next/server'
export async function POST(request) {
try {
const res = await request.json()
console.log('sddsdsdsd :',res)
return NextResponse.json(res)
} catch (error) {
// res.status(400).json({ message: " Something went wrong" });
}
}How to proof this is ok?
i did not get any console.log, even
console.log('sddsdsdsd :',res)@Finnish Spitz import { NextResponse } from 'next/server'
export async function POST(request) {
try {
const res = await request.json()
console.log('sddsdsdsd :',res)
return NextResponse.json(res)
} catch (error) {
// res.status(400).json({ message: " Something went wrong" });
}
}
How to proof this is ok?
You have to return a response in the error branch too, other than that lgtm
Open postman/thunderclient and make a post to the endpoint
Open postman/thunderclient and make a post to the endpoint
Finnish Spitz
actually im not sure about his code, is the logic true?
const handleFormSubmit = async (e) => {
e.preventDefault();
await fetch("/api/register", {
method: "POST",
body: JSON.stringify({email,password}),
headers: {
"Content-Type": "application/json",
},
});
};Should be good
Finnish Spitz
so if formSubmit it will fetch the register api, so the return of this function id whatever register route api return (?)
is it?
No… why would an event handler need to return something?
Finnish Spitz
ohhh, so what is the good explanation?
Good explanation of what?
Finnish Spitz
of what handleFormSubmit do
It sends a post to the /api/register thats it?
What are you even asking
Finnish Spitz
ahh forget it, actually my localhost/api/register is internal error 500
@Finnish Spitz ahh forget it, actually my localhost/api/register is internal error 500
Yeah cuz you are sending formdata
You have to send as json
Select “raw†there should be an option to select json underneath
Finnish Spitz
Nah its works
Finnish Spitz
this error happen again
actually it was work before, but when i check it again it war error
i have already check in postman, but it is error while before i was ok
i want user that registrated must be store in database, im using posgrate with prisma
my handleForm
const handleFormSubmit = async (e: any) => {
e.preventDefault();
const passwordHased = await hash(password, 12);
try {
const { data, error } = await supabase.auth.signUp({
email,
password: passwordHased,
});
console.log(data.user);
console.log(data.user?.email);
console.log(JSON.stringify({ email, password: passwordHased }));
await fetch("/api/register", {
method: "POST",
body: JSON.stringify({ email, password: passwordHased }),
headers: {
"Content-Type": "application/json",
},
});
if (error) {
alert("User have been registrated before!");
}
} catch (error) {
alert("Something went wront, Can not registration");
}
};my register route
export async function POST(request) {
try {
const res = await request.json()
const saveUser = await prisma.User.create({
data: res,
});
return NextResponse.json(saveUser)
}
catch (error) {
// res.status(400).json({ message: " Something went wrong" });
}
}