Patuqueso
Patuqueso

Reputation: 9

res.status is not a fumction

I am working on connecting my next app with google sheets, this is the function that handles the post request and I moved it to the following location "app/api/sheets" as the documentation suggest I should

import type { NextApiRequest, NextApiResponse } from 'next';
import { google } from 'googleapis'


type SheetForm = {
    name: string,
    city: string,
    phone: string
}

export async function POST(
    req: NextApiRequest,
    res: NextApiResponse
){
    if (req.method !== 'POST') {
        return res.status(405).send({ message: "Only POST requests are allowed"})
    }
    
    const body = req.body as SheetForm

    try {
        //prepare authentication
        const auth = new google.auth.GoogleAuth({
            credentials: {
                client_email: process.env.GOOGLE_CLIENT_EMAIL,
                private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\n/g, '\n')
            },
            scopes: [
                'https://www.googleapis.com/auth/drive',
                'https://www.googleapis.com/auth/drive.file',
                'https://www.googleapis.com/auth/spreadsheets'
            ]
        });

        const sheets = google.sheets({
            auth,
            version: 'v4'
        });

        const response = await sheets.spreadsheets.values.append({
            spreadsheetId: process.env.GOOGLE_SHEET_ID,
            range: 'Trabajo!A2:C',
            valueInputOption: 'USER_ENTERED',
            requestBody: {
                values: [
                    [body.name, body.city, body.phone]
                ]
            }
        });

        return res.status(200).json({
            data: response.data
        })

    }catch (err: any) {
        console.log(err)
        return res.status(500).send({ message: err.message ?? "Something went wrong" });
    }

}

And this is how I am fetching the API

  const [name, setName] = useState('')
  const [city, setCity] = useState('')
  const [phone, setPhone] = useState('')

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const form = {
      name,
      city,
      phone
    }

    const response = await fetch('/api/sheets', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(form)
    })

    const content = await response.json();

    console.log(content);
    alert(content.data.tableRange);

    setName('')
    setCity('')
    setPhone('')
  }

This gives me the following error "⨯ TypeError: res.status is not a function at POST (webpack-internal:///(rsc)/./app/api/sheets/route.ts:48:20)"

Upvotes: 0

Views: 72

Answers (1)

kfarkas
kfarkas

Reputation: 506

In next you it works in a little bit different than express. Since your method is named as POST, Next will handle the method allowance for you (you dont need to return 405).

When you return the response, the ideal way is to use NextResponse


return NextResponse.json(payload, { status: 200, statusText: 'OK' });

If you would like to return Http OK, then you can skip the second parameter, because it will fall back to that by default.

Upvotes: 0

Related Questions