如何克服ReactJS中的CORS问题 [英] How to overcome the CORS issue in ReactJS

查看:171
本文介绍了如何克服ReactJS中的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过我的React Application中的Axios进行API调用。但是,我在浏览器上遇到了这个CORS问题。我想知道我是否可以从客户端解决此问题,因为我没有内部访问API .Attached是我的代码。

I am trying to make an API call through Axios in my React Application.However, Iam getting this CORS issue on my browser. I am wondering if i can resolve this issue from a client side as i donot have any access to the API internally.Attached is my code.

const response = axios({
   method: 'post',
   dataType: 'jsonp',
   url: 'https://awww.api.com',
   data: {
    'appToken':'',
    'request':{ 
        'applicationName':'ddfdf', 
        'userName':'jaime@dfd.com', 
        'password':'dfd', 
        'seasonIds':[1521ddfdfd5da02] 
     }
     }
    });
   return{
    type:SHARE_REVIEW,
    payload:'response'
 }
 }

附件是我的WebPack.config.js

Attached is my WebPack.config.js

module.exports = {

entry: [
'./src/index.js'
 ],
output: {
  path: __dirname,
  publicPath: '/',
  filename: 'bundle.js'
},
module: {
 loaders: [{
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    presets: ['react', 'es2015', 'stage-1']
  }
 },
 { test: /\.json$/, loader: "json-loader"}]
  },
 resolve: {
  extensions: ['', '.js', '.jsx']
 },
devServer: {
historyApiFallback: true,
contentBase: './'
},
node: {
 dns: 'mock',
 net: 'mock'
 },
 };


推荐答案

理想的方法是为您添加CORS支持服务器。

The ideal way would be to add CORS support to your server.

您也可以尝试使用单独的 jsonp 模块。据我所知,axios不支持jsonp。所以我不确定你使用的方法是否有资格作为有效的jsonp请求。

You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.

还有另一个针对CORS问题的hackish工作。您必须使用nginx服务器部署代码,该服务器充当服务器和客户端的代理。
我们可以使用 proxy_pass 指令。配置您的nginx服务器,使处理您的特定请求的位置块 proxy_pass 或将您的请求重定向到您的实际服务器。
CORS问题通常是由于网站域名的变化而引起的。
当你有一个单独的代理服务器作为你客户端和服务器的面孔时,浏览器会误以为服务器和客户端位于同一个域中。 Ergo no CORS。

There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client. The thing that will do the trick us the proxy_pass directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass or redirect your request to your actual server. CORS problems usually occur because of change in the website domain. When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.

考虑这个例子。

你的服务器是 my-server .com ,您的客户 my-client.com
按如下方式配置nginx:

Your server is my-server.com and your client is my-client.com Configure nginx as follows:

// nginx.conf

upstream server {
    server my-server.com;
}

upstream client {
    server my-client.com;
}

server {
    listen 80;

    server_name my-website.com;
    access_log /path/to/access/log/access.log;
    error_log /path/to/error/log/error.log;

    location / {
        proxy_pass http://client;
    }

    location ~ /server/(?<section>.*) {
        rewrite ^/server/(.*)$ /$1 break;
        proxy_pass http://server;
    }
}

这里 my-website。 com 将是可访问代码的网站的最终名称(代理网站的名称)。
一旦nginx以这种方式配置。您需要修改请求,以便:

Here my-website.com will be the resultant name of the website where the code will be accessible (name of the proxy website). Once nginx is configured this way. You will need to modify the requests such that:


  • 所有API调用都从 my-server.com/<更改; API路径> my-website.com/server/<API-path>

  • All API calls change from my-server.com/<API-path> to my-website.com/server/<API-path>

如果您不熟悉nginx,我建议您浏览文档

In case you are not familiar with nginx I would advise you to go through the documentation.

要简要说明上述配置中发生的事情:

To explain what is happening in the configuration above in brief:


  • 上游定义请求将被重定向到的实际服务器

  • server block用于定义nginx服务器的实际行为。

  • 如果有多个服务器块,则 server_name 用于标识将用于处理当前请求的块。

  • error_log access_log 指令用于定义日志文件(用于调试)

  • 位置块定义处理不同类型的请求:

  • The upstreams define the actual servers to whom the requests will be redirected
  • The server block is used to define the actual behaviour of the nginx server.
  • In case there are multiple server blocks the server_name is used to identify the block which will be used to handle the current request.
  • The error_log and access_log directives are used to define the locations of the log files (used for debugging)
  • The location blocks define the handling of different types of requests:

  1. 第一个位置块处理以 / 开头的所有请求所有这些请求都被重定向到客户端

  2. 第二个位置块处理以 / server /< API-path> 开头的所有请求。我们会将所有此类请求重定向到服务器。

  1. The first location block handles all requests starting with / all these requests are redirected to the client
  2. The second location block handles all requests starting with /server/<API-path>. We will be redirecting all such requests to the server.


注意: / server 这里用于区分客户端请求和服务器端请求。由于域是相同的,因此没有其他区分请求的方法。请记住,没有这样的约定迫使您在所有此类用例中添加 / server 。它可以更改为任何其他字符串,例如。 / my-server /< API-path> / abc /< API-path> 等。

Note: /server here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server in all such use cases. It can be changed to any other string eg. /my-server/<API-path>, /abc/<API-path>, etc.

尽管这种技术应该可以解决问题,但我强烈建议您将CORS支持添加到服务器,因为这是这种情况的理想方式。处理。

Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.

如果您希望在开发过程中避免这样做,可以这个 chrome扩展名。它应该允许您在开发期间执行跨域请求。

If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.

这篇关于如何克服ReactJS中的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆