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

问题描述 投票:0回答:2

我是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 /动作/ 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
    };
}

有任何想法吗?

node.js reactjs heroku redux axios
2个回答
1
投票

您需要在服务器端启用cors,在那里发出请求,不可能从客户端覆盖cors设置,只有少数例外。


1
投票

试试这个:(将你的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();
});
© www.soinside.com 2019 - 2024. All rights reserved.