-1

I am trying to use the NextResponse from next/server. I am getting a status 500 and internal server error when i call the api. The condition. if (response.status === 202)is true and is able to enter the if block.

export async function POST(request: NextRequest) {
  let body = await request.json();
  console.log(body);
  if (process.env.URL_FILE_SERVICE_CREATE_CATEGORY) {
    axios.post(process.env.URL_FILE_SERVICE_CREATE_CATEGORY)
      .then(response => {
        if (response.status === 202) {
          return NextResponse.json({ hello: 'Next.js' })
        }
      })
      .catch(err => {
        if (err.response.status === 409) {
          return NextResponse.json({ message: "conflict" }, { status: 409 });
        } else {
          return NextResponse.json({ message: "Error" }, { status: 500 });
        }
      });
  }
}
George Jose
  • 166
  • 1
  • 1
  • 11

1 Answers1

1

The issue with the code snippet is that the axios.post call is not returned, which means that the function does not wait for the Promise returned by axios.post to be resolved or rejected before returning a response. This can lead to unexpected behavior because the response might be sent before the Promise is resolved or rejected. On the other hand, thecode snippet below includes a return statement before the axios.post call, which ensures that the function waits for the Promise to be resolved or rejected before returning a response. This is a better implementation because it guarantees that the response is only sent once the Promise is resolved or rejected.

`export async function POST(request: NextRequest) {
  let body = await request.json();
  
  if (process.env.URL_FILE_SERVICE_CREATE_CATEGORY) {
  return  axios.post(process.env.URL_FILE_SERVICE_CREATE_CATEGORY)
      .then(response => {
        if (response.status === 202) {
          return NextResponse.json({ hello: 'Next.js' }, { status: 409 })
        }
      })
      .catch(err => {
        if (err.response.status === 409) {
          return NextResponse.json({ message: "conflict" }, { status: 409 });
        } else {
          return NextResponse.json({ message: "Error" }, { status: 500 });
        }
      });
  }
}
`
George Jose
  • 166
  • 1
  • 1
  • 11