Encountering invalid JSON response while making an API request

Struggling to integrate GoToMeeting's API by sending a POST request to create a meeting. Currently, attempting to manually code the meeting body and send the necessary headers, but encountering an issue with invalid JSON error. Below is the code snippet for this particular route:

app.post('/new-meeting', (req, res) => {

  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application / json',
    Authorization: 'OAuth oauth_token=' + originalToken
  };

  console.log('-----------------------------------------------------------')
  console.log('Access Token:');
  console.log('OAuth oauth_token=' + originalToken);
  console.log('-----------------------------------------------------------')

  const meetingBody = {
    subject: 'string',
    starttime: '2018-03-20T08:15:30-05:00',
    endtime: '2018-03-20T09:15:30-05:00',
    passwordrequired: true,
    conferencecallinfo: 'string',
    timezonekey: 'string',
    meetingtype: 'immediate'
  };

  return fetch('https://api.getgo.com/G2M/rest/meetings', {
    method: 'POST',
    body: meetingBody,
    headers: headers
  }).then(response => {

    console.log('response:');
    console.log(response);


    response
      .json()
      .then(json => {
        res.send(json);
        console.log(req.headers);
      })
      .catch(err => {
        console.log(err);
      });
  });
});

Encountering the following error upon hitting the router:

{
  "error": {
    "resource": "/rest/meetings",
    "message": "invalid json"
  }
}

Any guidance or help on resolving this issue would be greatly appreciated!

Answer №1

Summary

The issue arises when passing a JavaScript object as the value for the body parameter in the fetch function. This results in the object being converted to a string using the .toString() method, which does not produce valid JSON. The solution is to use JSON.stringify() on the object before passing it as the body.

To resolve the problem, make the following adjustment:

body: JSON.stringify(meetingBody), 

Testing Scenario

This section showcases the issue and its resolution steps.

Server Setup

A basic mock of GoToMeeting's API has been created with an Express server that echoes back the request body received.

// Server code snippet
const express = require("express");
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.text({ type: "*/*" }));

// Echoing back the request body
app.post("/", (req, res) => {
    console.log(req.body);
    res.send(req.body)
});

app.listen(7070, () => console.log('Example app listening on port 7070!'))

Client Implementation

The client-side code has been tailored to showcase the issue encountered when sending a request to GoToMeeting's API. Only relevant sections for this demonstration have been retained.

// Client code snippet
const url = "http://localhost:7070/";
const fetch = require("node-fetch");

const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    Authorization: 'OAuth oauth_token=foobarbaz'
};

// Object representing meeting details
const meetingBody = {
    subject: 'string',
    starttime: '2018-03-20T08:15:30-05:00',
    endtime: '2018-03-20T09:15:30-05:00',
    passwordrequired: true,
    conferencecallinfo: 'string',
    timezonekey: 'string',
    meetingtype: 'immediate'
};

// Sending POST request to API
fetch(url, {
        method: 'POST',
        body: meetingBody,
        headers: headers
    })
    .then(res => res.text())
    .then(body => console.log(body));

Outcome of Test Execution

Both server and client logs display:

[object Object] 

This output is derived from calling meetingBody.toString().

By following the initial suggestion, the result changes to:

{"subject":"string","starttime":"2018-03-20T08:15:30-05:00","endtime":"2018-03-20T09:15:30-05:00","passwordrequired":true,"conferencecallinfo":"string","timezonekey":"string","meetingtype":"immediate"}

Now the data sent aligns with JSON format expected by the API.


Sidenote

MIME types should not include spaces. Consider revising Accept: 'application / json', to Accept: 'application/json',. While likely not significant in causing issues, it's best practice to adhere to standards.

Answer №2

In my opinion, the header appears to be inaccurate.

It is necessary to include 'Accept: application/json' without any spaces.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

The request header fails to function properly when used for cross-domain Ajax requests

I'm facing a challenge with adding a parameter in the request header. It works smoothly for calls within the same domain, but when making a call to a different domain (the API), I need to adjust the header parameter itself. Here is the snippet of cod ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Navigating through JSValue extracted from a JSON string

After obtaining a JSON String, I was able to convert it to a JSValue using Play framework. val name : String = "["Client_2","tClient_1","Client_NB"]" The resulting JSON, stored in the 'json' variable, looks like this: val json: JsValue = Json ...

Issues with Line Chart in D3: Scaling and Zoom not functioning as expected due to ClipPath limitations

I am utilizing D3 version 4 to process data and create a graph based on dates. Although I have successfully adjusted everything to be compatible with zoom functionality, I am struggling to prevent the line from extending beyond the chart axes. I would pre ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

Perform a toggle action on the first row when clicking within the current row using Jquery

I've been grappling with the idea of creating a function that can display and hide a comment field when a button is clicked. The challenge here is that there are multiple line items with their own comment boxes. I want to find a way to achieve this wi ...

Break up a list into separate paragraphs and style each word using individual CSS

I have a user-generated paragraph that consists of a list of words separated by commas, such as "dog, cat, hamster, turtle." I want to be able to individually assign attributes to each word in the list. Check out this image for reference In the example i ...

Guide on converting the <br> tag within a string to an HTML tag in VUE.js

When working with Vue.js, I often use {{}} to display my data on the HTML page. However, I recently encountered a situation where my data includes a string with tags that I would like to be rendered as actual HTML tags when displayed. data(){ return ...

Is there anyone who can clarify the operations happening within this Three.js StereoEffect code?

Is there anyone knowledgeable in stereo rendering who can provide an explanation of how these functions work together to achieve the VR stereo effect? Information on functions like StereoCamera(), setScissor(), setViewPort() in the three.js library seems s ...

Unable to access client's channels cache with empty parameters

In my quest to locate the guild and then channel within that guild, I have employed the following code snippet: const guild = client.guilds.cache.find(guild => guild.name === "bla bla bla"); const channel = guild.channels.cache.find(ch => c ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Every time Grunt detects newer files, it automatically triggers the imagemin:dynamic task

I am working with a Gruntfile that looks like this: grunt.initConfig({ imagemin: { dynamic: { files: [ src: ['lib/public/img/*.{png,jpg,jpeg,gif}'], dst: 'build/public/img/', expand: true, fl ...

Removing a parameter from a link in Vue.js: A step-by-step guide

I currently have the following list of URLs: http://example.com/post?st=1&plt=123&number=1 http://example.com/post?st=1&plt=[exp]&number=1 http://example.com/post/view/12?ex=1&plt=123 http://example.com/post/edit/12?ex=1&tes ...

Guide to successfully implement a POST action using jquery/ajax Colorbox! Check out the demo here

I stumbled upon a colorbox tutorial and attempted to replicate it with a POST action, but unfortunately, it just continues to load. Check out this fiddle The button represents the problematic POST action, while the text link is the original example that ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, ...

Instead of retrieving all associations, the focus will be on providing the total count of

Consider this scenario: an Object comprises numerous properties, while a property is linked to an Object. Currently, this is the established association. However, when I showcase all the objects using Object.all and include the :properties associations, th ...

methods for transferring global variable from view to controller in angularjs

Currently, I am facing an issue with sending backend data from EJS to the frontend controller of AngularJS. app.js I am passing data to view/indexcontents. var users = [ { name: 'john', email: '<a href="/cdn-cgi/l/email-pro ...