Issue encountered when retrieving a photo using the Places API: "Invalid JSON format detected at the start position."

Exploring the functionalities of the Google Places API has been my recent focus, however, I've encountered an obstacle that has me puzzled. While making API calls to a local proxy server, everything seems to be functioning well except when attempting to retrieve an image for a particular business.

I meticulously checked each part of the GET request URL by logging them in the console to ensure that they are concatenated correctly. Upon pasting the URL directly into the browser, it returns the expected result. It seems like there might be a generic code issue rather than a problem specific to the Places API itself. Any help in resolving this would be greatly appreciated.

The error generated from the terminal on the proxy server doesn't offer much insight, but perhaps someone can identify something that I may have overlooked:

undefined:1 ���� ^

SyntaxError: Unexpected token � in JSON at position 0

This is the front-end code snippet being used:

function makeAPICall(url) {
  return fetch(url);
}

makeAPICall(`http://localhost:5000/places/${searchString}`)
      .then(response => {
        return response.json();
      })
      .then(data => {
        responseObject = data.results;
        renderResult(responseObject[10]);

        return responseObject[10];
      })
      .then(responseObject => {
        makeAPICall(`http://localhost:5000/place/image/${responseObject.photos[0].photo_reference}`)
          .then(response => {
            return response.json();
          })
          .then(photoData => {
            console.log(photoData);
          });
      });

The following section showcases the proxy server's code (excluding operational routes not related to the issue):

require('dotenv').config({path: '../.env'});

const express = require('express');
const request = require('request');

const GOOGLE_API_KEY = process.env.API_KEY;
const placesImgURL = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=';

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/place/image/:query', (req, res) => {
  request(
    { url: `${placesImgURL}${req.params.query}&key=${GOOGLE_API_KEY}` },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        console.log(response);
      }

      res.json(JSON.parse(body));
    }
  )
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

UPDATE:

An error within the server code occurs at this line:

res.json(JSON.parse(body));

A network call screenshot captured from the dev tools interface is available here: https://i.stack.imgur.com/0Zv4r.png

Upon examining the line that triggers the error through console logging, I'm presented with an extensive log:

// Extremely long log output removed due to space constraints

Answer №1

The issue at hand is that the request library seems to have been deprecated. By switching to another library like axios, the code below based on your own should work without any issues:

const express = require('express')
const axios = require('axios')

const url = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=YOUR_API_KEY"

const getData = async (url) => {
  try {
    const response = await axios.get(url)
    const data = response.data
    console.log('data', response.data)
  } catch (error) {
    console.log('error', error)
  }
}

const app = express()
const port = 3000

app.get('/', async (req, res) => {
  res.send(await getData(url))
})

app.listen(port, () => {})

Output:

Response GET / status=200
"data"
"����\u0000\u0010JFIF\u0000\u0001\u00…01b`J+]�Ǥ�%�„c����8�\u001fb\u0017/��..."

Additionally, the response is an image; so there's no need to format it as json in the backend. You can utilize the client-side service for this.

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

"Error message received while attempting an HTTP GET request in Node.js

When attempting to make an HTTP GET request, I encountered the following error. Can anyone provide guidance on how to resolve this issue? var https = require('http'); var options = { host: 'lifecycle-dev.elasticbeansta ...

"Step-by-step guide: Accessing the upload folder in Node.js with Express

I successfully implemented an upload feature in my API using multer. However, I'm facing issues while trying to access the uploaded files from Gatsby. router.use("/public", express.static(__dirname + "/public")); The uploaded files are located in /pu ...

What is the reason behind Node.js Express invoking the "close" method on POST requests with data before finalizing the request closure?

I have developed a streaming server using Node.js and Express to send data in chunks through a POST endpoint. However, I've noticed that the request close event is being triggered as soon as there is data in the request, even though I have not explici ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Randomly, an AJAX request sent from Internet Explorer 11 to a node.js server operating behind an Apache proxy may abruptly terminate

When using angular on a webpage, a get request is initiated to retrieve json data after a user action. The issue arises when attempting this request on Internet Explorer 11, as it fails randomly while working smoothly on Firefox. Below is a screenshot of t ...

Execute code once gulp task has been completed for all files

I've been experimenting with Gulp to compare its speed with Grunt, and I'm quite impressed with the results. However, there's one thing I'm unable to figure out how to do in Gulp. Specifically, I have this gulp task for minifying HTML: ...

Obtaining Font Information using Node.js

Is there a way to retrieve the Description section of a font's properties, as seen when you right-click on the file? https://i.stack.imgur.com/rwnLw.png I am specifically looking for details related to the Title attribute. I tried using the get-fil ...

Download files using ajax in express framework

Is there a way to initiate file download in response to an ajax post request without actually downloading the file? $(function(){ $('img.download').click(function() { var image_path = $(this).attr('class').split(" ")[1] $.aja ...

What advantages can I gain from serving my React application through my Express server?

After researching how to render a React app from an express server, I'm wondering what the advantages are of doing so? I've already created a React app and used an express server to communicate with my database. I would run my express server and ...

When attempting to deploy my application on Heroku, I encountered the error message "ReferenceError: require

My NodeJS project works fine locally but encounters issues when deployed on Heroku. Upon running "heroku logs --tail" for error checking, the following message is displayed: 2020-08-18T10:39:44.396002+00:00 app[web.1]: const express = require('expres ...

Exploring the challenges of setting up Node in an attempt to unravel AngularJs 1.5

I recently started reading a book called "Unraveling AngularJS 1.5" in order to expand my knowledge on Angular development. Early on in the book, the author suggests installing Node.js, so I went ahead and did that. When I ran Node on the command prompt, i ...

Warning: Unhandled promise rejection - The type error occurred because the property 'close' of the object is undefined

I am currently configuring node.js in order to test my JavaScript codes using the Jest JavaScript testing framework. Can anyone spot what I might have done incorrectly? package.json file { "name": "institute-jest", "version&quo ...

A guide on compiling Sass without using gulp and Laravel Elixir [SOLUTION]

If you encounter an error similar to this one: https://i.stack.imgur.com/ZqVeV.png You have come to the right place :) ...

Having trouble importing AnimeJS into an Ionic-Angular project

I successfully added AnimeJS to my Ionic 4 project using the commands below: npm i animejs --save npm i @types/animejs --save To reference AnimeJS, I used the following import statement: import * as anime from 'animejs' However, whenever I tr ...

Utilizing Node.JS and Typescript to correctly define database configuration using module.exports

I am currently utilizing Mongoose in my node.js application, which is written in Typescript. The Mongoose documentation provides clear instructions on how to connect to their database like this, but I prefer to have the configuration stored in a separate ...

Why won't my test in WebdriverJS and Jasmine redirect the browser to the intended URL?

Currently, I am executing a test suite with the following setup: nodejs selenium-webdriver jasmine-node (utilizing jasmine 1.3) Upon running the spec provided below, the browser window initializes but fails to redirect to the specified URL - instead, it ...

res.json cannot be called

I have a file that contains the following function which returns JSON data. I am trying to call this function from another file. exports.me = function(req, res) { var userId = req.user._id; User.findOne({ _id: userId }, function(err, user) { ...

Can you explain to me the relationship between Node.js and Angular? Is it primarily for creating APIs or does

I've been trying to find information on Google about this, but I haven't found a satisfactory answer. Can someone explain the role of Node.js and ExpressJS in MEAN stack development? Is it similar to PHP for creating APIs that Angular will then c ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...

There are no connection events being triggered - using Mongoose version 4.7.1 with Express

My current struggle involves establishing a connection from my express app to MongoDB via Mongoose. Despite the simplicity of the setup, which is as basic as it gets: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhos ...