Search code examples
javascriptreactjsnode.jsexpressspotify

Server API endpoint not reached


For some reason, I am not able to reach the API endpoint from server.js. Using Spotify API. Here is my server.js:

// server.js
const express = require('express');
const app = express();
const dotenv = require('dotenv').config()

const clientSecret = secret
const clientId = id

app.use(express.json());

// PARAMS
const authParameters = {
    method: 'POST',
    headers: {
        'Content-Type' : 'application/x-www-form-urlencoded',
    },
    body: 'grant_type=client_credentials&client_id=' + clientId + '&client_secret=' + clientSecret
}

app.get('/message', (req, res) => {
    res.json({ message: "Hello from server!" })
})

app.get('/spotify/token', async (req, res) => {

  try {
    // Fetch data from the Spotify APIa
    const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
    console.log("DATA!!!!", data)
    res.json(data)

  } catch (error) {
    console.error('Ran into an error:', error)
    res.status(500).json({ error: 'Server error' })
  }
});

const PORT = 3000
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
});

Here is my package.json:

{
  "name": "music-playlist-transfer-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "nodemon": "^3.0.1"
  }
}

Here is the use of that function on my client-side:

const getToken = async () => {

    const data = await fetch('/spotify/token')
    console.log(data)
    const result = await data.json(data)
    console.log(result)
    
    return result.access_token
}

export default getToken

Here is the use of that function in the front-end:

import React, { useEffect } from "react"
import getToken from "../api/getToken"
import { Button } from "@mui/material"

const LandingPage = () => {

  const handleTestButton = async () => {
    console.log("here")
    const token = await getToken()
    console.log(token)
    return token
  }

  return (
    <>
    <Button onClick={() => handleTestButton()} variant={"outlined"}>asd</Button>
    </>
  )
}

export default LandingPage

I am using Nodemon to start the server. Whenever I try to click the button to test the API call, I get an error: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data and the object: Response { type: "basic", url: "http://localhost:5173/spotify/token", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers(8), body: ReadableStream, bodyUsed: false } getToken.js:20:13

I've used the identical code in the front-end work and it gave me the access token needed.

The object I receive in the terminal when I visit http://localhost:3000/spotify/token is:

DATA!!!! Response {
  [Symbol(realm)]: null,
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: true,
    requestIncludesCredentials: true,
    type: 'default',
    status: 400,
    timingInfo: {
      startTime: 3310.630542039871,
      redirectStartTime: 0,
      redirectEndTime: 0,
      postRedirectStartTime: 3310.630542039871,
      finalServiceWorkerStartTime: 0,
      finalNetworkResponseStartTime: 0,
      finalNetworkRequestStartTime: 0,
      endTime: 0,
      encodedBodySize: 85,
      decodedBodySize: 0,
      finalConnectionTimingInfo: null
    },
    cacheState: '',
    statusText: 'Bad Request',
    headersList: HeadersList {
      cookies: [Array],
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: [ [URL] ],
    body: { stream: undefined }
  },
  [Symbol(headers)]: HeadersList {
    cookies: [
      '__Host-device_id=AQBrs3chlvJceJxn00EzwIWmJ3pi3HP1dnVssqyrBWAgMdxpAwGR4y6KkZ56p8n0yzebgru7AxscYPa1PavGUtJkTaQEW-EBsNU;Version=1;Path=/;Max-Age=2147483647;Secure;HttpOnly;SameSite=Lax',
      'sp_tr=false;Version=1;Domain=accounts.spotify.com;Path=/;Secure;SameSite=Lax'
    ],
    [Symbol(headers map)]: Map(13) {
      'date' => [Object],
      'content-type' => [Object],
      'set-cookie' => [Object],
      'sp-trace-id' => [Object],
      'x-envoy-upstream-service-time' => [Object],
      'server' => [Object],
      'strict-transport-security' => [Object],
      'x-content-type-options' => [Object],
      'content-encoding' => [Object],
      'vary' => [Object],
      'via' => [Object],
      'alt-svc' => [Object],
      'transfer-encoding' => [Object]
    },
    [Symbol(headers map sorted)]: null
  }
}

The JSON I get is an empty object. Not really sure what's going on, insight would be greatly appreciated! Thanks.


Solution

  • On this line:

    const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
    

    The variable data is now a promise so to access the returned value of that promise you need convert data to JSON if you want to send it to the client. Just update like so:

    const data = await fetch('https://accounts.spotify.com/api/token', authParameters)
    console.log("DATA!!!!", data)
    res.json(await data.json())