55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import axios from 'axios';
|
|
import { cookies } from 'next/headers'
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
export const POST = async (request: NextRequest) => {
|
|
// INTERPOLATING API URL OF BACKEND
|
|
const url: string = `${process.env.NEXT_PUBLIC_API_URL}/auth/login`
|
|
// GET REQUEST BODY
|
|
const {username, password} = await request.json();
|
|
|
|
try {
|
|
// MAKE AN API REQUEST
|
|
/*
|
|
* - WE USE AXIOS INSTEAD OF FETCH
|
|
* - FETCH ALWAYS RETURNS "TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is already closed"
|
|
* WHEN WE RUN "response.json()"
|
|
*/
|
|
const response = await axios(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
data: JSON.stringify({
|
|
userName: username,
|
|
password,
|
|
})
|
|
})
|
|
|
|
|
|
if (response?.data ?? false) {
|
|
const token: string = response.data.data.token;
|
|
const expired = response.data.data.expired;
|
|
const data = {
|
|
username: response.data.data.username,
|
|
token
|
|
}
|
|
cookies().set({
|
|
name: 'credential',
|
|
value: JSON.stringify(data),
|
|
httpOnly: false,
|
|
sameSite: 'strict',
|
|
path: '/',
|
|
maxAge: expired
|
|
})
|
|
}
|
|
return NextResponse.json(response.data, { status: response.status });
|
|
} catch (error: unknown) {
|
|
if (axios.isAxiosError(error)) {
|
|
return NextResponse.json(error.response?.data || { message: 'Unknown error' }, { status: error.response?.status || 500 });
|
|
}
|
|
return NextResponse.json({ message: 'An unexpected error occurred' }, { status: 500 });
|
|
|
|
}
|
|
} |