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

标签 node.js reactjs heroku redux axios

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

有什么想法吗?

最佳答案

试试这个:(将你的 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();
});

关于node.js - 启用 CORS - Node.js + React/Redux + Axios 部署在 Heroku 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903743/

相关文章:

node.js - 在 node.js 中使用 imagemagick 将 svg 转换为 png

javascript - Nodejs 中 undefined variable 无法显示错误

reactjs - 如何更新饼图上的系列

google-app-engine - PaaS 中的 SOA 云可能吗?

heroku - 无法将 ruby​​ on Rails 应用程序推送到 Heroku - 网络问题?

mongodb - 如何在 node.js 中将数据转换为 utf-8?

node.js - Apollo GraphQL 中的上下文与 RootValue

javascript - 我如何使用 ReactJS 代码播放和暂停 React-gif 图像

javascript - 无法从源读取图像的高度/宽度

java - Heroku 容器 :release throwing UnhandledPromiseRejectionWarning: