How to use Yelp-Fusion Library on React and Express (CORS Policy)
Tags: react, express, webdev, api
Published: 2022-07-25 17:51:00

I was recently working on a personal project that involved displaying restaurants and [YELP API](https://www.yelp.com/developers/documentation/v3/get_started) was definitely one of the best options to choose from. Besides the official documentation, when you are trying to play around with API responses, I recommend that you refer to this [post](https://spectralops.io/blog/yelp-api-guide/) and test the endpoints with postman. 

My project is not a big project so I tried to get away with not creating a server and just fetching the API only on the client side. To cut to the chase, it did not work out for mainly one reason. The [CORS Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

One way to temporarily avoid the CORS policy and fetching on the client side was to use [heroku anywhere](https://www.npmjs.com/package/cors-anywhere#client), but this was not a stable way to fetch the api for the following reasons.

1. Not having a server is not stable. Even though the backend of my project did not require a database nor any user information, not having a server could end up being a mere frontend template.

1. Everything would have worked out even though not having a server is not preferred if heroku anywhere was supported as it was, but the heroku team decided to limit the usage of heroku anywhere for various reasons. [This link](https://github.com/Rob--W/cors-anywhere/issues/301) provides a comprehensive analysis to why the heroku dev team decided to limit the usage of the heroku anywhere. Thus, the only way to get around the CORS policy on the frontend side was using heroku anywhere for my project, and if they only grant me access for a limited amount of time, my webpage will basically be useless after a certain amount of time. For further reference, please take a look at [this github discussion](https://github.com/Yelp/yelp-fusion/issues/579).

1. Last but not least, why not build a server if it is not complicated? All I had to do was to create an API endpoint for my client, and this endpoint simply fetches business from the YELP API business endpoint.

The frameworks I have chosen for my project were React for the client side, and Express for the server side. Simple as that.

I started out by creating a simple Express app.

```js
const express = require('express')
const app = express()
const port = 3001
const cors = require('cors');
const yelp = require('yelp-fusion');
const apiKey = 'YOUR-API-KEY';
const client = yelp.client(apiKey);
```
Just for clarification, I am using the [yelp-fusion library](https://github.com/Yelp/yelp-fusion). 
To avoid the CORS policy, I installed the [cors library](https://expressjs.com/en/resources/middleware/cors.html).
This is my `package.json` file.

```json
{
    "name": "backend",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "devStart": "nodemon app.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "cors": "^2.8.5",
        "express": "^4.18.1",
        "request": "^2.88.2",
        "yelp-fusion": "^3.0.0"
    },
    "devDependencies": {
        "nodemon": "^2.0.19"
    }
}

```
Now to use the cors library, all you have to do is call the `app.use()` function on your app.

```js
app.use(cors());
```
Afterwards, just create your API endpoint using `app.get()`. I did not need any views so I decided to `send()` my `res`.
```js
app.get('/api', (req, res) => {
    client.search({
        location: 'PUT-ANY-LOCATION',
        // offset: '0',
        // limit: '50'
    }).then(response => {
        console.log(JSON.stringify(response.jsonBody));
        res.send(response.jsonBody.businesses);
    }).catch(e => {
        console.log(e);
    });
})
```

This code snippet should now send your desired data to the server.
On the frontend, I fetched from my API endpoint but had to parse the data as such.
```js
const fetchData = () => {
		fetch('YOUR-API-ENDPOINT')
		.then(response => response.json())
		.then(data => JSON.stringify(data))
		.then(stringifiedData => JSON.parse(stringifiedData))
		.then(parsedData => {
			setRestaurant(parsedData);
			setRestaurantName(parsedData[0].name)
		})
		.catch((error) => {
			console.log(error);
		});
	}
```

This is it! Since I'm relatively new to web development, I struggled to figure out a way to get around the CORS policy, and this was one simple way to do so. I hope this article helps who are getting into webdev and are struggling with any pertinent issues.

Any other suggestions would be greatly appreciated as well.