I cant post with axios to my server
Answered
Ojos Azules posted this in #help-forum
Ojos AzulesOP
I am trying to post my appointment to my server with axios
Code:
In my database i get the data but i get those errors in on my front end store so my POST request gets failed. Why i cant post it when i get the data in my backend website?
Code:
const bookAppointment = async () => {
if (
!formData.name ||
!formData.email ||
!formData.phone ||
!formData.barber ||
!formData.service ||
!formData.date ||
!formData.time
) {
toast.error("Some fields are not filled!");
return;
}
try {
await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/appointments`, {
clientName: formData.name,
clientEmail: formData.email,
clientPhone: formData.phone,
barber: formData.barber,
barberId: formData.barberId,
serviceId: formData.serviceId,
service: formData.service,
day: formData.date,
time: formData.time,
});
} catch (error) {
// Handle error
toast.error("Failed to book appointment. Please try again later.");
}
};In my database i get the data but i get those errors in on my front end store so my POST request gets failed. Why i cant post it when i get the data in my backend website?
61 Replies
Hackberry nipple gall parasitoid
Ojos AzulesOP
i use firefox :/
@Hackberry nipple gall parasitoid https://chromewebstore.google.com/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf
you can download it
This is a hack, proper way to fix is add cors headers in your backend server
if you use express, use
cors libraryOjos AzulesOP
This is my route handler for POST
@averydelusionalperson
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function POST(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
const userId = auth();
const body = await req.json();
const { clientName, clientEmail, clientPhone, barber, barberId, service, serviceId, day, time} = body;
console.log(body);
if (!userId) {
return new NextResponse("Unauthenticated", { status: 401 });
}
if (!clientName) {
return new NextResponse("Client name is required", { status: 400 });
}
if (!clientEmail) {
return new NextResponse("Client email is required", { status: 400 });
}
if (!clientPhone) {
return new NextResponse("Client phone is required", { status: 400 });
}
if (!barber) {
return new NextResponse("Barber is required", { status: 400 });
}
if (!service) {
return new NextResponse("Service is required", { status: 400 });
}
if (!day) {
return new NextResponse("Day is required", { status: 400 });
}
if (!time) {
return new NextResponse("Time is required", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const storeByUserId = await db.appointment.findFirst({
where: {
id: params.storeId,
barberId,
},
});
if (!storeByUserId) {
return new NextResponse("Unauthorized", { status: 403 });
}
const appointment = await db.appointment.create({
data: {
clientName,
clientEmail,
clientPhone,
barber,
barberId,
service,
serviceId,
day,
time,
storeId: params.storeId
},
});
return NextResponse.json(appointment, { headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}});
} catch (error) {
console.log("[APPOINTMENTS_POST]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}@averydelusionalperson
the code is really fucked up
anyways, you're posting to your own api route?
from Next.js app dir?
Ojos AzulesOP
i am posting from another website
@averydelusionalperson the code is really fucked up
Ojos AzulesOP
Thanks
you can add headers in next config file
so, you don't need to repeat everytime
Ojos AzulesOP
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// output: "export",
// images: {
// loader: "custom",
// loaderFile: './image-loader.js'
// },
async headers() {
return [
{
source: "/api/:path*",
headers: [
{
key: "Access-Control-Allow-Origin",
value: "*", // Set your origin
},
{
key: "Access-Control-Allow-Methods",
value: "GET, POST, PUT, DELETE, OPTIONS",
},
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, Authorization",
},
],
},
];
},
}
module.exports = nextConfiglike this?
you can ig
Ojos AzulesOP
ok
i will try now to post
still 403 error
tried restarting the server?
Ojos AzulesOP
yy
Btw this is not vulnerable to attacks for my website?
async headers() {
return [
{
source: "/api/:path*",
headers: [
{
key: "Access-Control-Allow-Origin",
value: "*", // Set your origin
},
{
key: "Access-Control-Allow-Methods",
value: "GET, POST, PUT, DELETE, OPTIONS",
},
{
key: "Access-Control-Allow-Headers",
value: "Content-Type, Authorization",
},
],
},
];
},I don't think so, but if you only want your origins to allowed to access api, you can add that in value
Ojos AzulesOP
Its weird because i get values in my route.ts but in front end store i get 403 error
you can see the console?
Ojos AzulesOP
it has to do with axios?
are you able to access it from like postman or smthing?
Ojos AzulesOP
Oh you mean this url?
http://localhost:3000/api/id/appointments
that i post
yeah
Ojos AzulesOP
yes i get the appointments
GET works well
Ojos AzulesOP
Ojos AzulesOP
i use thunderclient
status code?
post full response
Ojos AzulesOP
Status: 500 Internal Server Error
seems like your route issue
Answer
not cors
fix it
Ojos AzulesOP
yy maybe
export async function POST(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
const userId = auth();
const body = await req.json();
const { clientName, clientEmail, clientPhone, barber, barberId, service, serviceId, day, time} = body;
console.log(body);
if (!userId) {
return new NextResponse("Unauthenticated", { status: 401 });
}
if (!clientName) {
return new NextResponse("Client name is required", { status: 400 });
}
if (!clientEmail) {
return new NextResponse("Client email is required", { status: 400 });
}
if (!clientPhone) {
return new NextResponse("Client phone is required", { status: 400 });
}
if (!barber) {
return new NextResponse("Barber is required", { status: 400 });
}
if (!service) {
return new NextResponse("Service is required", { status: 400 });
}
if (!day) {
return new NextResponse("Day is required", { status: 400 });
}
if (!time) {
return new NextResponse("Time is required", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const storeByUserId = await db.appointment.findFirst({
where: {
id: params.storeId,
barberId,
},
});
if (!storeByUserId) {
return new NextResponse("Unauthorized", { status: 403 });
}
const appointment = await db.appointment.create({
data: {
clientName,
clientEmail,
clientPhone,
barber,
barberId,
service,
serviceId,
day,
time,
storeId: params.storeId
},
});
return NextResponse.json(appointment);
} catch (error) {
console.log("[APPOINTMENTS_POST]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}I cant understand where is the error
As you can see i get the body
idk man, check the error log
you have it there
Ojos AzulesOP
cool cool
thanks!
console.log("[APPOINTMENTS_POST]", error);so, the problem is solved?
Ojos AzulesOP
yes my friend i found what was the error
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function POST(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
const userId = auth();
const body = await req.json();
const { clientName, clientEmail, clientPhone, barber, barberId, service, serviceId, day, time} = body;
console.log(body);
if (!userId) {
return new NextResponse("Unauthenticated", { status: 401 });
}
if (!clientName) {
return new NextResponse("Client name is required", { status: 400 });
}
if (!clientEmail) {
return new NextResponse("Client email is required", { status: 400 });
}
if (!clientPhone) {
return new NextResponse("Client phone is required", { status: 400 });
}
if (!barber) {
return new NextResponse("Barber is required", { status: 400 });
}
if (!service) {
return new NextResponse("Service is required", { status: 400 });
}
if (!day) {
return new NextResponse("Day is required", { status: 400 });
}
if (!time) {
return new NextResponse("Time is required", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const storeByUserId = await db.store.findFirst({
where: {
id: params.storeId,
},
});
if (!storeByUserId) {
return new NextResponse("Unauthorized", { status: 403 });
}
console.log(storeByUserId);
const appointment = await db.appointment.create({
data: {
clientName,
clientEmail,
clientPhone,
barberId,
serviceId,
day,
time,
storeId: params.storeId
},
});
return NextResponse.json(appointment);
} catch (error) {
console.log("[APPOINTMENTS_POST]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function GET(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const appointments = await db.appointment.findMany({
where: {
storeId: params.storeId,
},
});
return NextResponse.json(appointments);
} catch (error) {
console.log('[APPOINTMENTS_GET]', error);
return new NextResponse("Internal Error", { status: 500 });
}
}
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function POST(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
const userId = auth();
const body = await req.json();
const { clientName, clientEmail, clientPhone, barber, barberId, service, serviceId, day, time} = body;
console.log(body);
if (!userId) {
return new NextResponse("Unauthenticated", { status: 401 });
}
if (!clientName) {
return new NextResponse("Client name is required", { status: 400 });
}
if (!clientEmail) {
return new NextResponse("Client email is required", { status: 400 });
}
if (!clientPhone) {
return new NextResponse("Client phone is required", { status: 400 });
}
if (!barber) {
return new NextResponse("Barber is required", { status: 400 });
}
if (!service) {
return new NextResponse("Service is required", { status: 400 });
}
if (!day) {
return new NextResponse("Day is required", { status: 400 });
}
if (!time) {
return new NextResponse("Time is required", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const storeByUserId = await db.store.findFirst({
where: {
id: params.storeId,
},
});
if (!storeByUserId) {
return new NextResponse("Unauthorized", { status: 403 });
}
console.log(storeByUserId);
const appointment = await db.appointment.create({
data: {
clientName,
clientEmail,
clientPhone,
barberId,
serviceId,
day,
time,
storeId: params.storeId
},
});
return NextResponse.json(appointment);
} catch (error) {
console.log("[APPOINTMENTS_POST]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function GET(
req: Request,
{ params }: { params: { storeId: string } }
) {
try {
if (!params.storeId) {
return new NextResponse("Store ID is required", { status: 400 });
}
const appointments = await db.appointment.findMany({
where: {
storeId: params.storeId,
},
});
return NextResponse.json(appointments);
} catch (error) {
console.log('[APPOINTMENTS_GET]', error);
return new NextResponse("Internal Error", { status: 500 });
}
}
Original message was deleted