Rehan
Rehan

Reputation: 4013

NextJS API not posting to external domains

I have a simple NextJS app running in Vercel. I cloned the NextJS template given by Vercel and added just one file called jira.js

I am just trying to post random data to external API when this jira is hit.

Jira.js is the following

    // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    
    import axios from 'axios'
    import https from 'https'
    
    export default (req, res) => {
        const headers = {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }
    
        axios.post('https://webhook.site/6db7a14b-48d7-4037-a482-86885526aa40', {
            Name: 'Fred',
            Age: '23'
        }, {
            headers: headers,
            withCredentials: true
        }
        ).then(function(res) {
            console.log({res: res})
        }).catch(function(e) {
            console.log({"failed": e})
        })
        res.json({ status: 'ok' })
    
    }

When I try it locallly (localhost:3000/api/jira), the data is getting posted to the Webhook site, but when I deploy it to vercel(random-domain.com/api/jira) then there is no posting of data in webhook site, but I get Status: ok messsage in the browser.

I am pretty new to this? Can somoene guide me with what I am missing?

Upvotes: 2

Views: 2302

Answers (1)

leerob
leerob

Reputation: 3157

You haven't marked your function as async, so I don't believe it's waiting for the response back from JIRA. For example:


export default async (req, res) => {
  try {
    const response = await fetch(
      `https://webhook.site/6db7a14b-48d7-4037-a482-86885526aa40`,
      {
        body: JSON.stringify({
            Name: 'Fred',
            Age: '23'
        }),
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json'
        },
        method: 'POST'
      }
    );

    if (response.status >= 400) {
      return res.status(400).json({
        error: 'There was an error'
      });
    }

    return res.status(200).json({ status: 'ok' });
  } catch (error) {
    return res.status(500).json({
      error: 'There was an error'
    });
  }
};

You also don't need axios - fetch is polyfilled for you by default.

Upvotes: 2

Related Questions