Troubleshooting a 400 error code in the context of a Bad

I'm facing an issue while trying to retrieve a list of flights using Google's QPX Express API. I keep receiving a bad request response that has me puzzled:

{ StatusCodeError: 400 - {"error":{"errors":[{"domain":"global","reason":"badRequest","message":"Invalid inputs: received empty request."}],"code":400,"message":"Invalid inputs: received empty request."}}

Could it be possible that there is an error in the way I am structuring my request? I am utilizing the request-promise library for this operation.

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',

  qs: {
   "request": {
     "passengers": {
       "adultCount": 1 },
       "slice": [{"origin": "BOS",
                  "destination": "LAX",
                  "date": "2017-03-01"
                }]
              }
        },
    json: true
}

request(options)
  .then(function (response) {
    console.log(response)
  })
  .catch(function (err) {
    console.log(err)
  })

Answer №1

Hooray! The problem has been successfully resolved. I discovered that the request needed to include the data within the body key and have the content-type set to JSON.

As a result, the API now delivers the expected data.

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?&key=XXXXXXXXXXXXXXXXXXXX',
  body: {
    "request": {
      "passengers": {
        "adultCount": "1"
      },
      "slice": [
        {
          "origin": "SFO",
          "destination": "LAX",
          "date": "2017-06-19"
        }
      ],
      "solutions": "1"
    }
  },
  json: true
}

request(options)
  .then(function (response) {
    console.log(response.trips.tripOption[0].saleTotal)
  })
  .catch(function (err) {
    console.log(err)
  })

Answer №2

Take a look at this:

const options = {
  method: 'POST',
  uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',

  qs: {
   "request": {
     "passengers": {
       "adultCount": 1 },
       "slice": [{"origin": "BOS",
                  "destination": "LAX",
                  "date": "2017-03-01"
                }]
              }
        },
    json: true
};

request(options)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  });

Make sure to properly close the uri string and don't forget those semicolons.

Update: Consider using:

request({
    url: (your url here),
    method: "POST",
    json: requestData
},

where you will replace requestData with your qs object.

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

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Iterating through elements with JavaScript and dynamically replacing them in the HTML code

I'm struggling with the code I found on CodePen and need some help with it since I'm not very good with JS. How can I prevent the items from repeating endlessly? Currently, they scroll indefinitely with 20 items per 'page' before the ...

Organize the array based on the grandchild's value

Consider this scenario: I have a collection of objects, where each object contains another collection of objects. The structure is as follows: [ { "dislikes": [ { "createDate": { "date": 11, ...

Having difficulty transferring mathematical algorithms from JavaScript to Java

Having difficulty translating JavaScript code that converts between Latitude/Longitude & OS National Grid Reference points to Java. () Encountering variations in the results of certain mathematical operations. The javascript and java code snippets pro ...

selecting a radio button and saving its value into a JavaScript variable

How can I assign the return value from a JavaScript script function to a variable inside the HTML body? The function will return the selected variable, but how can I assign it to a variable within my HTML body? <body> <form action="somepage.php ...

Ways to prevent PySpark from_json from displaying a complete null row when reading a CSV file with JSON typed columns containing null attributes

I'm currently experiencing an issue that I hope to articulate clearly. I'm attempting to parse a CSV file using PySpark. This CSV file contains some JSON columns. The JSON columns have a consistent schema, but the way they are filled varies. Fo ...

Unable to access the data once CORS is disabled

After enabling cors, I successfully loaded the data. However, when I disabled it, I encountered issues retrieving the data. Is there a way to bypass this without turning on cors? An error message I received is: createHttpLink.js:96 Refused to connect to & ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

`Troubles encountered when using findAndModify with MongoDB and Node.js`

Currently I am enrolled in an online MongoDB course that seems to be a bit outdated, as it is using version 1.4 while I have upgraded to version 3.0. I am encountering some difficulty with the following code snippet, which I have attempted to update to ma ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Unable to retrieve response from Node Express using Ajax when uploading files with Multer

Currently, I am utilizing multer for image uploads and it is functioning flawlessly. While I can view the data being printed to the console, I am uncertain about how to capture and manipulate this data within the browser. Presented below is my code snippet ...

Tips on incorporating a color picker in HTML using jQuery

Looking to implement an HTML color picker with the help of JQuery. Wondering if there is a simpler method to do this without relying on external JQuery libraries? Experimented with <input type="color"> but encountered issues that prevented it from ...

Struggling with implementing the PUT method in Nodejs/Express and unable to make it

I've been working on my initial node app, which is a rest api. Everything seems to be functioning well except for the PUT method. I have tried various combinations and consulted both older and newer tutorials, but I am struggling with updating the rec ...

Is it possible to update only the inner text of all elements throughout a webpage?

Scenario After coming across a thought-provoking XKCD comic, I decided to craft a script that would bring the comic's concept to life: javascript:var a=document.getElementsByTagName('body')[0].innerHTML;a=a.replace(/Program(\w\w+ ...

Is there a method available to calculate the quantity of columns in an angular grid?

I need to customize my angular grid to limit the number of columns displayed on screen to a maximum of 5 at a time. Even if there are more than 5 columns available, I want to restrict the user from showing more than 5. Is it possible to achieve this by set ...

Exploring the Functionality of worker-loader Inline

It was my understanding that the Webpack worker-loader configuration below: ... module: { rules: [ { test: /worker\.js/, loader: "worker-loader", options: { inline: 'fallba ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

How to Parse a JSON Object with Variable Fields in C#

I have a json document that looks like this: { "name": "bert", "Bikes": { "Bike1": { "value": 1000, "type": "Trek" }, "Bike2": { "value&q ...

Having trouble with a React child component not reacting to a click event?

The current issue I am experiencing is that the component is not triggering a click event when the button is clicked. TickerPage render() { return ( <div className="TickerPage"> <div className="TickerPage-container"> <b ...

Exploring hierarchical information within a JSON response from a Wiki API

As a newcomer to this field, I am currently exploring ways to access Wikipedia's API for extracting the value of "extract" and adding it to an HTML element dynamically. The challenge lies in the fact that the information is subject to change based on ...