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

When making a fetch call in React, the response is the index.html file but Chrome displays an error saying Uncaught (in promise) SyntaxError: Unexpected token < in JSON

I have been encountering an issue while trying to retrieve data from my local express server and displaying it using React. The problem appears to be that instead of fetching the data, the index.html of the React app is being returned. In the network tab o ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Implementing key strokes in an HTML input field within a geckoWebBrowser

I am currently using the "geckoWebBrowser1" component to navigate to a URL that displays a login textbox with the ID: login-email Although I have successfully inserted "[email protected]" into the aforementioned textbox, it is essential to simulate k ...

Tips for securely saving JSON data to a file within a GitHub workflow?

I have a workflow on GitHub that retrieves information about all the GitHub Releases in my repository and then uses jq to process the JSON response. The problem I'm facing is that my shell code struggles with single quotes present in the JSON data at ...

Deactivate the submit button when the form is not valid in angularjs

I am currently facing a challenge with my form that contains multiple input fields. To simplify, let's consider an example with just two inputs below. My goal is to have the submit button disabled until all required inputs are filled out. Here is wha ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

the typeahead.js method in Twitter's process() function is filling the list with undefined values

I am encountering a similar issue as described in the thread Twitter Typeahead Ajax results undefined. Since that problem remains unresolved, I am revisiting the topic with hopes of shedding light on any missing details. My setup includes standalone Typea ...

Update the text for the filter search placeholder in the Ant Table component

Is there a way to alter the default placeholder text in the Ant Table? I've set up a functioning example in documentation but couldn't find any prop for customization besides the customized filter dropdown, which I didn't want to implement. ...

Using JSON in an AJAX request to log in

Currently, I am in the process of developing a straightforward login form that utilizes AJAX for server communication and PHP as the server-side script. However, I have encountered some challenges while trying to send login data to the server via JSON. Th ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Verifying the data format retrieved is JSON or is not a valid format with the help of Spring Boot

My goal is to determine the data format being retrieved from a REST endpoint. I want to ensure that the API only responds to requests with JSON data format. To achieve this, I plan to identify the data format from the retrieved header. The structure of th ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

What is the method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes: Vue.js v2.0.3 vue-router v2.0.1 vuex v0.8.2 In routes.js, there is a basic interceptor setup router.beforeEach((to, from, next) => { if (to.matched.some(record ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...