POST request using fetch in Next.Js

Hello Freshworks Community!

Today, I’m trying to send a POST request to a Freshdesk API but i’m not having much luck. I’ve managed to get it working using curl and Postman, but I can’t get it to work in Next.Js using the fetch method. My code is as follows:

import base64 from 'base-64'

export default async (req, res) => {
    try {
      const response = await fetch(
        `https://endpoint.freshdesk.com/api/v2/tickets/28/reply`,
        {
          body: "We are working on this issue. Will keep you posted.",
          headers: {
            'Authorization': 'Basic ' + base64.encode("APIKEY:X"),
            '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'
      });
    }
  };

When i try to POST this, it just gives me a 400 error, but i’m not sure why. Is my body incorrect? Maybe the headers are missing something?

Anyone with experience with Next.Js or Fetch who can help me?

@kloneman,
Good day! Welcome to the community!
I have some suggestions on the code snippet

  1. Can you try using our Platform’s request API?

if you want to use the Fetch then the body value which you are passing might be wrong,

try this instead :point_down:
let data = { "body":"We are working on this issue. Will keep you posted." }

body: JSON.stringify(data),

Hope it helps :slight_smile:

Thanks

1 Like

@Santhosh

Thank you for your reply.

I tried the change you made and now I’m getting a new error saying “415 Unsupported Media Type”

Here are my response headers if you need them:

Headers {
  [Symbol(map)]: [Object: null prototype] {
    date: [ 'Thu, 20 Jan 2022 16:44:41 GMT' ],
    'content-type': [ 'application/json' ],
    'transfer-encoding': [ 'chunked' ],
    connection: [ 'keep-alive' ],
    status: [ '415 Unsupported Media Type' ],
    'x-request-id': [ 'bd8a5640-2e6c-40e6-9460-abdafdd738bf' ],
    'x-rack-cache': [ 'invalidate, pass' ],
    'x-xss-protection': [ '1; mode=block' ],
    'x-content-type-options': [ 'nosniff' ],
    'x-fw-ratelimiting-managed': [ 'true' ],
    'x-ratelimit-total': [ '160' ],
    'x-ratelimit-remaining': [ '158' ],
    'x-ratelimit-used-currentrequest': [ '1' ],
    'x-envoy-upstream-service-time': [ '22' ],
    'x-trace-id': [ '00-48b38ad480b516e3753f2b50fac7aee5-8180561f2733408b-00' ],
    server: [ 'fwe' ]
  }
}

Okay so I got it working finally. I had to add this to the headers:

“Content-Type”: “application/json; charset=utf8”

Thank you for your help Santhosh :slight_smile:

2 Likes

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.