Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS - Node.js + React/Redux + Axios deployed on Heroku

I'm new to React, please keep this in mind. For learning purposes I have built a simple React + Redux application that fetches data from an external API in JSON format.

Everything works fine if I manually enable CORS in Chrome (via extension).

Now, I deployed the application to Heroku and I need to permanently enable CORS to be able to access the API. Apparently this is more complicated then I thought!

Here'my code:

server.js

const express = require('express');
const port = process.env.PORT || 8080;
const app = express();
const path = require('path');
const cors = require('cors');

app.use(cors());
app.use(express.static(__dirname + '/'));

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);

console.log("server started");

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from "redux-promise";
import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('.container'));

src/actions/index.js

import axios from 'axios';

const API_KEY = "********************************";
export const SEARCH_URL = `https://food2fork.com/api/search?key=${API_KEY}`;
export const FETCH_RECIPES = "FETCH_RECIPES";

export function fetchRecipes(searchTerm) {
    const url = `${SEARCH_URL}&q=${searchTerm}`;
    const request = axios.get(url);

    return {
        type: FETCH_RECIPES,
        payload: request
    };
}

Any ideas?

like image 433
Scaccoman Avatar asked Nov 02 '25 18:11

Scaccoman


2 Answers

Try this: (change your app.use(CORS()) to this)

app.use(function (req, res, next) {

   // Website you wish to allow to connect
   res.setHeader('Access-Control-Allow-Origin', '*');

   // Request methods you wish to allow
   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

   // Request headers you wish to allow
   res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

   // Set to true if you need the website to include cookies in the requests sent
   // to the API (e.g. in case you use sessions)
   res.setHeader('Access-Control-Allow-Credentials', true);

   // Pass to next layer of middleware
   next();
});
like image 54
Przemek eS Avatar answered Nov 04 '25 10:11

Przemek eS


You need to enable cors on server side, where you make the request, it is not possible to override cors settings from client, with few exceptions.

like image 40
Mosè Raguzzini Avatar answered Nov 04 '25 09:11

Mosè Raguzzini