使用 API 和另一个来源 (CORS) 的 React 应用程序

React app using API with another origin (CORS)

我有一个 React 应用程序,它在另一个域上使用 java ee 后端休息服务器,运行。我启用了 CORS:

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Headers : origin, content-type, accept, authorization
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age : 1209600

我正在像这样使用 react with fetch:

export function get(path, headers) {
    return fetch(apiUrl + path, {
        "metod" : "GET",
        "headers" : headers,
        "credentials" : "include"
    })
}

我的 React 应用在 http://localhost:3000 上 运行。 当我登录时,服务器 returns Set-Cookie,但该 cookie 不包含在对服务器的任何进一步请求中,除非我再次尝试登录。然后它包含在该特定登录请求中。

有什么建议吗?

安装这个。

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=es

安装后,单击他的 BrowserIcon 并打开。这就是全部。您将不会收到更多错误。

编辑。生产解决方案 如果你想从你的服务器配置它(或者只是不添加浏览器扩展,试试这个:)

  • 如果您正在使用 node.js,请执行以下操作:node.js 服务器文件:response.writeHead(200, { 'Content-Type': contentType, 'Access-Control-Allow-Origin': '*' })

  • fetch('http://ajax.googleapis.com/ajax/services/feed/load?v=‌​1.0&num=8&q=http://r‌​ss.cnn.com/rss/editi‌​on_entertainment.rss‌​?output=rss', { method: 'get', mode: 'no-cors', }).then(() => { console.log('Works!'); });

  • 其他 solution:If 您也在使用 PHP 您可以添加: <?php header('Access-Control-Allow-Origin: *'); ?> 到您的 PHP 文件中。如我所见,情况并非如此,所以...在您的服务器(例如:Apache)中添加此指令:Header set Access-Control-Allow-Origin * in Settings(作为第一个选项)。

所以,我通过使用另一个 Whosebug 线程和 robertklep 的评论解决了这个问题。如所述 here:"When working on localhost, the cookie domain must be omitted entirely."。我实现了 robertkleps 的想法,但没有设置域。它产生了一个像这样的 Set-Cookie:Set-Cookie:kek=7fukucsuji1n1ddcntc0ri4vi; Version=1; Path=/; Max-Age=100000。这很好用。

我只是想分享一下我是如何通过这个 post 让我的本地开发变得轻松的,如果你正在使用 create-react-app 只需将你的主要 API url 代理添加到你的 package.js 例如 "proxy": "http://localhost:8080/API" 无需在后端设置 CORS。

添加更多现有答案。

通过 React,您可以在 package.json 中使用 "proxy" 来避免 CORS。 基本上,如果您需要在 localhost:3000

上达到 localhost:8100(您的 java 后端)并且您的 React 应用程序 运行

您可以设置:

In your package.json

"proxy": "http://localhost:8100"

然后当您想到达 /hello 时,这将是您 java API 的终点,您可以这样做:

import axios from 'axios';

axios.get('/hello')
  .then(resp => {
    console.log(resp.data);
  });

它会被重定向到 http://localhost:3000/hello 这样你就可以避免 CORS。