启用 CORS - Node.js + React/Redux + 部署在 Heroku 上的 Axios

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

我是 React 的新手,请记住这一点。 出于学习目的,我构建了一个简单的 React + Redux 应用程序,它以 JSON 格式从外部 API 获取数据。

如果我在 Chrome 中手动启用 CORS(通过扩展),一切正常。

现在,我将应用程序部署到 Heroku,我需要永久启用 CORS 才能访问 API。 显然这比我想的要复杂!

这是我的代码:

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
    };
}

有什么想法吗?

您需要在发出请求的服务器端启用 cors,除了少数例外,无法从客户端覆盖 cors 设置。

试试这个:(将你的 app.use(CORS()) 改成这个)

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();
});