简体   繁体   中英

How to convert lambda function into a next.js api friendly function?

I have a Instagram api making calls to my personal profile and ran as a lambda function from netlify which goes like this:

require('isomorphic-unfetch')

const url = `https://www.instagram.com/graphql/query/...`

async function getPosts() {...}

exports.handler = async function (event, context, callback) {
   const posts = await getPosts()
   callback(null, {
       statusCode: 200,
       headers: {
           'Content-Type': 'application/json',
       },
       body: JSON.stringify(posts),
   })
}

I am rebuilding the site using Next.js and migrating my site to vercel and want to run the serverless function from /pages/api/insta.js but Next.js throws an error as it expects something along the lines of:

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction

// export default (req, res) => {
//   res.statusCode = 200
//   res.json({ name: 'John Doe' })
// }

Ok lads, managed to resolve the issue by conversion to the following code - posting it in case someone else comes across the same issue:

export default async function handler(req, res) {
    const posts = await getPosts()
    res.statusCode = 200
    res.setHeader('Content-Type', 'application/json')
    res.end(JSON.stringify(posts))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM