Next.js Discord

Discord Forum

Error: Failed to parse URL from "/api/create"

Answered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
I am sending a request to my API route in the server function
Answered by Ray
it is expecting _id, name, description but you pass chnl_id, chnl_name, chnl_desc
View full answer

42 Replies

Alligator mississippiensisOP
"use server";

export async function create(formData: FormData) {
    const res = await fetch("/api/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: formData,
      });
    
    return res.json();
}
how can I solve this issue?
Error: Failed to parse URL
usually, this error is cause by fetching own api in a server component without absolute url
Alligator mississippiensisOP
<form className="space-y-10 md:w-[500px]" action={create}>
        <Input
          value={id}
          name="chnl_id"
          variant="faded"
          classNames={{
            inputWrapper:
              "h-[50px] dark:bg-neutral-800 dark:text-[#999] bg-neutral-200 text-[#888]",
            label: "dark:text-white/70 text-black",
          }}
          labelPlacement="inside"
          type="text"
          label="Channel ID"
          placeholder=""
        />
        <Input
          isRequired
          onChange={handleChange}
          name="chnl_name"
          variant="faded"
          classNames={{
            inputWrapper:
              "h-[50px] dark:bg-neutral-800 dark:text-white bg-neutral-200 text-black",
            label: "dark:text-white/70 text-black",
          }}
          labelPlacement="outside"
          type="text"
          label="Channel name"
          placeholder="e.g. Welcomers"
        />
        <Input
          isRequired
          name="chnl_desc"
          variant="faded"
          classNames={{
            inputWrapper:
              "h-[50px] dark:bg-neutral-800 dark:text-white bg-neutral-200 text-black",
            label: "dark:text-white/70 text-black",
          }}
          labelPlacement="outside"
          type="text"
          label="Description"
          placeholder="e.g. Come and say hello!"
        />
        <Autocomplete
          name="category"
          isRequired
          defaultItems={channel_categories}
          label="Category"
          labelPlacement="outside"
          placeholder="e.g. Technology"
          classNames={{
            base: "h-[50px]",
          }}
          variant="faded"
        >
          {(category) => (
            <AutocompleteItem key={category.label} value={category.value}>
              {category.label}
            </AutocompleteItem>
          )}
        </Autocomplete>
        <SubmitButton />
      </form>
ah i see
can you move the code in "/api/create" to the server action instead?
since you are using server action, you don't need the api route
Alligator mississippiensisOP
why?
if you really want to do this
"use server";

export async function create(formData: FormData) {
    const res = await fetch("http://localhost:3000/api/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: formData,
      });
    
    return res.json();
}
keep in mind that you would need to change the url when building the production build
Alligator mississippiensisOP
what are you returning in the api route
Alligator mississippiensisOP
export async function POST(req:NextRequest, res:NextResponse) {
    const formData = await req.formData();
    const { chnl_id, chnl_name, chnl_desc, category } = formData as unknown as TChannel;

    await connect();
    const existing_channel = await Channels.findOne({chnl_id});
    if(existing_channel) { //if there is an existing channel with the same email
        return new NextResponse("Channel is already created", {status:400}) //throw a Next.js Response with an error
    }

    if(!chnl_id || !chnl_name || !chnl_desc || !category) {
        return new NextResponse("Invalid Data", {status:422})
    }

    const newChannel = new Channels({
        chnl_id,
        chnl_name,
        chnl_desc,
        category,
    })

    try {
        await newChannel.save();
        return NextResponse.json("Channel is created",{status:200})
        
    } catch (error) {
        console.log(error)

        return NextResponse.json({message: "Server error"},{status:500})

    }

} 
the server action can only return a serializable arguments and values
your api route return other response
@Ray can you move the code in `"/api/create"` to the server action instead?
that's why i suggest you to do this
Alligator mississippiensisOP
ok, i will do it
response is OK, but I can't see any data in my db
export async function create(formData: FormData) {
    const { chnl_id, chnl_name, chnl_desc, category } = formData as unknown as TChannel;


    if(!chnl_id || !chnl_name || !chnl_desc || !category) {
        return { error: 'Invalid Data' }
    }

    await connect();
    const existing_channel = await Channels.findOne({chnl_id});
    if(existing_channel) { //if there is an existing channel with the same email
        return { error: 'Channel is already created' } //throw a Next.js Response with an error
    }

    const newChannel = new Channels({
        chnl_id,
        chnl_name,
        chnl_desc,
        category,
    })

    try {
        await newChannel.save();
        return { message: "Channel is created" }
        
    } catch (error) {
        console.log(error)

        return { message: "Server error" }

    }
}
    const { chnl_id, chnl_name, chnl_desc, category } = Object.fromEntries(formData) as unknown as TChannel;
Alligator mississippiensisOP
still the same thing happens.
export async function create(formData: FormData) {
  console.log(Object.fromEntries(formData))
...
}
Alligator mississippiensisOP
it doesn't log anything mate.
on the server console no?
Alligator mississippiensisOP
wait
@Ray on the server console no?
Alligator mississippiensisOP
yeah
then it might be something wrong with this check
 if(!chnl_id || !chnl_name || !chnl_desc || !category) {
        return { error: 'Invalid Data' }
    }
@Alligator mississippiensis Click to see attachment
since you get the invalid data error response
Alligator mississippiensisOP
@Ray do you know mongoose ?
yes
Alligator mississippiensisOP
errors: {
description: ValidatorError: Path description is required.
at validate (
properties: [Object],
kind: 'required',
path: 'description',
value: undefined,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
},
name: ValidatorError: Path name is required.
at validate (C:\Users\shukur.huseynli\Documents\vscode_projects\chatwithme\node_modules\mongoose\lib\schemaType.js:1364:13)
at SchemaType.doValidate
},
_id: ValidatorError: Path _id is required.
at validate
properties: [Object],
kind: 'required',
path: '_id',
value: undefined,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
}
},
_message: 'Channel validation failed'
}
my server console
but I am sure that I haven't overlooked these before
@Ray on the server console no?
Alligator mississippiensisOP
btw it logs all of my formData
it is expecting _id, name, description but you pass chnl_id, chnl_name, chnl_desc
Answer
Alligator mississippiensisOP
it works now
thank you very much Ray
i am closing this conversation