Next.js Discord

Discord Forum

POST returns 405 Not Allowed

Answered
Greenish Elaenia posted this in #help-forum
Open in Discord
Greenish ElaeniaOP
When form submit is run, I get Error 405 Not Allowed back in browser console.
In the VSCode terminal running the project at localhost:3001, I'm seeing this printed in terminal:
✓ Compiled /api/auth/login in 267ms (329 modules)
⨯ Detected default export in '...\app\api\auth\login\route.ts'. Export a named export for each HTTP method instead.
⨯ No HTTP methods exported in '...\app\api\auth\login\route.ts'. Export a named export for each HTTP method.

What is blocking the Post request?

/app/login/page.tsx
<form action={handleSubmit}>
<input type="text" name="usernameInput" id="usernameInput"/>
<input type="password" id="pwInput" name="pwInput" ></input>
<button type="submit" > Login </button>
</form>

async function handleSubmit(formData: { get: (arg0: string) => any; }) {
const usernameInput = formData.get("usernameInput");
const pwInput = formData.get("pwInput");

const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ usernameInput, pwInput }),
});
}
}

/app/api/auth/login/route.ts
import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';
import { NextApiRequest, NextApiResponse } from 'next'
import { hashPassword } from "@/utils/PasswordHasher";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { usernameInput, pwInput } = req.body
if (!usernameInput || !pwInput) {
throw new Error('username and password required');
}
const hash = await hashPassword(pwInput);
const result =
await sqlSELECT TOP 1 * FROM users WHERE username = ${usernameInput} AND pw = ${hash};;
return NextResponse.json( {result}, { status: 200, statusText: "OK"} );
}
Answered by Greenish Elaenia
/app/api/auth/login/route.ts needs to export a named function POST
solution:
export async function POST(req: NextApiRequest, res: NextApiResponse) {
View full answer

2 Replies

Greenish ElaeniaOP
Solution found thanks to gtp-help
Greenish ElaeniaOP
/app/api/auth/login/route.ts needs to export a named function POST
solution:
export async function POST(req: NextApiRequest, res: NextApiResponse) {
Answer