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.