Having trouble retrieving Yelp Fusion using an express backend

Attempting to retrieve Yelp data within my backend using Express and then saving the data in the state for frontend use has presented a challenge. When making the request, an error is thrown displaying

AxiosError: Request failed with status code 400
in the backend terminal.

The following code snippet can be found in my backend Express routes/api folder for Yelp, where the term refers to the name passed in from the frontend.

const express = require('express');
const router = express.Router();
const axios = require('axios');


router.post('/:item', async (req, res) => {

    axios.get("https://api.yelp.com/v3/businesses/search",{
        headers: {
            Authorization: `Bearer lwP3BHKGDyMyjAEaSTV7CVWpnJyQYLH0CAVGzRxdxrwgPbV0GK52UBmBIRbRTcletnrfIVukKlseH5ze2Xojp8wr8alq9GVOFXITEyLBh2h9RS3445nZmUW6t7JpY3Y`
        },
        params: {
            term: req.params.item,
            location: "nyc"
        }
    })
        .then(response => {
            return res.json(response.data.businesses)
        })
        .catch(err => {
            console.log(err)
        })

})


module.exports = router;


The resulting error message displayed in the terminal:

{
  message: 'Request failed with status code 400',
  name: 'AxiosError',
 	description: undefined,
  number: undefined,
	fileName: undefined,
	lineNumber: undefined,
	columnNumber: undefined,
	stack: 'AxiosError: Request failed with status code 400\n' +
	' at settle (/Users/ronnydeng/Desktop/Classwork/MERN/Meals4You/backend/node_modules/axios/dist/node/axios.cjs:1268:12)\n	' + 
	' at IncomingMessage.handleStreamEnd (/Users/ronnydeng/Desktop/Classwork/MERN/Meals4You/backend/node_modules/axios/dist/node/axios.cjs:2446:11)\n	' + 
	' at IncomingMessage.emit (node:events:539:35)\n	' + 
	' at endReadableNT (node:internal/streams/readable:1345:12)\n	' + 
	'at processTicksAndRejections (node:internal/process/task_queues:83:21)',
	config: {
	    transitional: {
	        silentJSONParsing: true,
			forcedJSONParsing: true,
			 clarifyTimeoutError: false
	    },
	    adapter: [Function: httpAdapter],
	     transformRequest: [[Function: transformRequest]],
		  transformResponse: [[Function: transformResponse]],
		   timeout: 0,
		    xsrfCookieName: 'XSRF-TOKEN',
		     xsrfHeaderName: 'X-XSRF-TOKEN',
			  maxContentLength: -1,
			   maxBodyLength: -1,
			    env: { FormData: [Function], Blob: null},
			     validateStatus: [Function: validateStatus],
		     	headers: AxiosHeaders {
				     	Authorization: 'Bearer lwP3BHKGDyMyjAEaSTV7CVWpnJyQYLH0CAVGzRxdxrwgPbV0GK52UBmBIRbRTcletnrfIVukKlseH5ze2Xojp8wr8alq9GVOFXITEyLBh2h9RS3445nZmUW6t7JpY3Y',
					     'User-Agent': 'axios/1.1.3',
						    'Accept-Encoding': 'gzip, deflate, br',
						       [Symbol(defaults)]: [Object]
					      },
					       params: { term: 'Pizza', location: 'nyc' },
					        method: 'get',
						     url: 'https://api.yelp.com/v3/businesses/search',
						      data: undefined
  },
  	code: 'ERR_BAD_REQUEST',
	status: 400
}

In order to avoid hitting limits with CORS Anywhere when fetching from the frontend, I aim to make requests directly from the backend instead.

Answer №1

Switch up your request method from POST to GET. After a brief review of the Fusion developer documentation, I was able to successfully query Fusion using this simple call:

var fetch = require('node-fetch');

const url = 'https://api.example.com/data';
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Insert your API key and test it out for yourself;

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

How can I disable or get rid of vhost in Express.js?

Situation Description I am managing a server that has only one IP address and running multiple virtual domains on the same port using express.vhost. app.listen(80); app.use(express.vhost('www.example.com', require ...

Dynamic updating in a React application with an express server

Currently, I have set up a boilerplate for a MERN application with an express server on the backend and react on the frontend. My goal is to implement hot reloading in my app so that changes in the react code can be reflected without needing to refresh the ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

Cypress has the ability to exclude certain elements from its testing

How do I locate a clickable element using the cypress tool? The clickable element always contains the text "Login" and is nested inside the container div. The challenge lies in not knowing whether it's an <button>, <a>, or <input type=& ...

utilizing loop to incorporate javascript callback

I am just starting to learn about asynchronous programming and I'm facing a challenge that I can't seem to solve. In my node.js app, I am working on serving stock quotes. The task involves querying a database for details of various companies, sen ...

I'm trying to locate information on the implementation of the mongodb connect function. Where might I be

When I ctrl+clicked on the MongoClient.connect method to see how it's implemented, I discovered that the driver (npm i mongodb) is written in TypeScript. Despite this, all I could locate were multiple versions of the method (overloaded functions), an ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

How to Display Graph Horizontally using jqBarGraph

I have encountered a minor but significant issue while using jqBarGraph. Due to the limited space available for displaying the graph (550px width with unlimited height), and up to 50 items can be shown at once, the bars appear quite small (around 5px thi ...

Mapping objects in an array with React.js

I have a JavaScript file that I am attempting to map. I want to map it to specific buttons, but I am having trouble with it. Can you please help me? I have tried several options, but nothing seems to work in my case {DlCards.map((dvlcards, cardtitle, link ...

How can JavaScript be used to parse an HTML string and convert it into tabular data in the form of a 2D array

My goal is to parse an HTML string client-side using React with TypeScript as our frontend framework. During the parsing process, I need to extract the styles associated with each element, whether it be inline styles, inherited styles, or styles defined wi ...

I'm having trouble accessing my POST data using console.log. Instead of getting the expected data, all I see in the console when I try to GET is "

My code for the POST function is working, but when I try to retrieve and display the POST response from the server, all I get is "null". Can anyone help me figure out how to properly send data from my form to the server and then successfully console log it ...

Remove files from a folder and eliminate references in a separate list in a different database

I have two collections, one for reviews and one for users. In the users collection, there is an array called reviews, which contains the _ids of the reviews from the reviews collection. Sometimes, I find myself deleting reviews from the reviews collection ...

Rendering dynamic HTML content using EJS

I've created a blog application using Express and MongoDB, with EJS for rendering the data. My issue lies in the styling of the content to resemble a paragraph: <div class="show-post__content"> <%= post.body %> </div> The po ...

A dynamic star rating plugin in jQuery that allows for partial star ratings

Can you offer some guidance? I've searched on google but couldn't find anything helpful. I'm looking for a star rating system for my website that can display an initial value with decimals (like 2.75 displaying as 3/4 of a star) while only a ...

Accessing database values for dropdown menus using JavaScript

Please provide guidance on how to populate a dropdown with values from a database in this code snippet, which is used to create dynamic rows in a table. <script type="text/javascript"> $(document).ready(function(){ $(".add-row").click(function() ...

Adjust the minimum height and width when resizing the window

Apologies in advance if this has already been addressed, but I have tried solutions from other sources without success. My Objective: I aim to set the minimum height and width of a div based on the current dimensions of the document. This should trigger ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Is there a way to retrieve all values in the pathname from a URL after the initial slash

Extracting pathname pathname: "/kids/dlya-malyshey/platya-i-yubki" By using the substr function, I will remove the initial slash location.pathname.substr(1,); Now, the result is kids/dlya-malyshey/platya-i-yubki The challenge is to extract all ...

"How to include a JavaScript file from the node_modules folder in an Angular project

Currently, I am working on integrating an npm package called svgedit into my angular app. The installation of the package was successful; however, when attempting to reference a JavaScript file, I encountered the following error: net::ERR_ABORTED 404 ( ...