Search code examples
node.jsexpressoauth-2.0ejsspotify

How to fix, "{ error: { status: 400, message: 'Bad search type field tracks' } }" occurred while using Spotify Search API


  • Back-end on: node.js, express. Other modules used: body-parser, request.

  • I am trying to fetch track ID from Spotify Search API.

  • A user makes a POST request. The request is fed to the server.

  • The server makes GET request to the endpoint.

  • The endpoint returns data.

  • The data is parsed to JSON.

Problem: Upon parsing, following error is logged into the terminal.

{ error: { status: 400, message: 'Bad search type field tracks' } }

Code to focus on:

request({
    url: searchUrl,
    headers: {
      "Authorization": token
    }
  }, function(err, res) {
    if (res) {
      var data = JSON.parse(res.body);
      // var spotifyTrackIdAppJs00 = data.tracks.items[0].id;
      console.log(data);
      // console.log(trackId);
    }
)

Complete app.js code:

// It is a nodejs, expressjs project.
const express = require("express");

// 'body-parser' is used to access tags from the html file. We'll be using it to access queryValue.
const bodyParser = require("body-parser");

// request package; to fetch data from search endpoint.
const request = require("request");

// This app constant is created to be able to access the menthods available in 'express' package.
const app = express();

// 'urlencoded' helps access html data. Other data formats could JSON etc.
// body-parser required as to exclusively define "extended: true" although this is no use to us.
app.use(bodyParser.urlencoded({
  extended: true
}));

// This sets a static directory to look for source files like css, js, img. These file links are mentioned in html or ejs files.
// A folder named 'public' has to be in the same directory as "app.js". The source files are stored here.
app.use(express.static("public"));

// ejs view engine has been used to use app.js variables into the output ejs file.
app.set('view engine', 'ejs');

// Variable(s) to store the data fetched from API endpoint.
var data = "";

// The page to load when the browser (client) makes request to GET something from the server on "/", i.e., from the homepage.
// This GET request is made as soon as the homepage url is entered in the address bar od browser, automatically.
app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

// The data that server should POST when the POST request is sent by the client, upon entering the search queryValue, in the search bar (form).
app.post("/", function(req, res) {

  // The user input query. We are using body-parser package here.
  const query = req.body.queryValue;

  // Follow procedure here to get access_token and refresh_token: https://benwiz.com/blog/create-spotify-refresh-token/
  const access_token = {access_token};
  const token = "Bearer " + access_token;
  var searchUrl = "https://api.spotify.com/v1/search?q=" + query + "&type=tracks&limit=4";

  request({
    url: searchUrl,
    headers: {
      "Authorization": token
    }
  }, function(err, res) {
    if (res) {
      var data = JSON.parse(res.body);
      // var spotifyTrackIdAppJs00 = data.tracks.items[0].id;
      console.log(data);
      // console.log(trackId);
    }

    // res.render("results", {
    //   spotifyTrackIdEjs00: spotifyTrackIdAppJs00
    // });
    // console.log("Value to be used in rendered file: " + spotifyTrackIdAppJs00);
  })
});

// Starting the server. Should this be placed at the top of all other commands?
app.listen(3000, function() {
  console.log("Server is running on port 3000.")
});

Helpful Resources:

I am an absolute beginner. Please teach me like I'm five. I would be highly grateful to you.


Solution

  • Your code looks fine, but you have one typo that is messing up all. This one:

    var searchUrl = "https://api.spotify.com/v1/search?q=" + query + "&type=tracks&limit=4";
    
    

    The Spotify's API's parameter type have the following valid valued: album , artist, playlist, track, show and episode.

    On your searchUrl, you are using tracks (plural) instead of track, so it should be:

    var searchUrl = "https://api.spotify.com/v1/search?q=" + query + "&type=track&limit=4";
    
    

    For the future: the HTTP's 400 code means "Bad Request", meaning that server is telling you that something is being sent wrong on the request. When you get that kind of error response, usually is good to double check the required params/body of the API you are consuming and their accepted values