无标题文章

## React项目中基本配置及常见坑的解决

### 一、创建React项目

```xml-dtd

# 全局安装脚手架

npm install create-react-app -g --save

# 创建React项目

create-react-app my-app

```

### 二、实现Less文件的加载

#### 1、暴露配置文件

```xml-dtd

# 暴露项目的配置文件

npm run eject

```

- 暴露配置文件后的目录结构

#### 2、安装插件

```xml-dtd

# 安装less、less-loader插件

npm install less less-loader --save

```

#### 4、修改配置文件

- 修改  `config/webpack.config.js`  的文件

```js

// style files regexes

const cssRegex = /\.css$/;

const cssModuleRegex = /\.module\.css$/;

const sassRegex = /\.(scss|sass)$/;

const sassModuleRegex = /\.module\.(scss|sass)$/;

// 新增less变量

const lessRegex = /\.less$/;

const lessModuleRegex = /\.module\.less$/;

```

如图:

再在 `cssModuleRegex `和 `sassModuleRegex` 之间添加如下代码:

```js

// 编译less文件

{

  test: lessRegex,

  exclude: lessModuleRegex,

  use: getStyleLoaders(

    {

        importLoaders: 2,

        sourceMap: isEnvProduction && shouldUseSourceMap,

    },

    'less-loader'

  ),

  sideEffects: true,

},

{

  test: lessModuleRegex,

  use: getStyleLoaders(

    {

      importLoaders: 2,

      sourceMap: isEnvProduction && shouldUseSourceMap,

      modules: {

          getLocalIdent: getCSSModuleLocalIdent,

      },

    },

    'less-loader'

  ),

},

```

如图:

- OK 可以正常加载less文件

### 三、实现 AntdUI 组件的按需加载

#### 1、安装插件

```xml-dtd

# 安装 按需加载的插件

npm install -g babel-plugin-import --save

```

#### 2、修改配置文件

- 修改  `config/webpack.config.js`  的文件

```js

plugins: [

  [

// 按需加载antd组件

    "import",

    {

        "libraryName": "antd",

        "style": true

  }

  ]

],

```

如图:

- OK 已经实现按需加载antd组件

### 四、配置 AntdUI 主题

#### 1、修改配置文件

- 修改  `config/webpack.config.js`  的文件,加上如下内容

```js

if (preProcessor) {

      let loader = {

        loader: require.resolve(preProcessor),

        options: {

          sourceMap: shouldUseSourceMap

        }

      };

      // 定制antd主题

      if (preProcessor === 'less-loader') {

        loader.options.modifyVars = {

          "@primary-color": "#40A9FF"

        };

        loader.options.javascriptEnabled = true;

      }

  loaders.push(loader);

}

```

如图:

- OK 重启后主题生效

### 五、本地请求跨域-设置代理

#### 1、下载插件

```xml-dtd

# 安装http-proxy-middleware包

npm install http-proxy-middleware --save

```

#### 2、新建 `setupProxy.js `文件

- 在项目  `src 根目录`  下创建名叫  `setupProxy.js` 的文件

配置如下内容:

```js

let proxy = require('http-proxy-middleware');

// 本地代理

module.exports = function(app) {

  app.use(

      '/mock',

      proxy.createProxyMiddleware(

        {

          target: 'http://yapi.demo.qunar.com/mock/80992/react-antd',

          changeOrigin: true,

          pathRewrite: {

            '^/mock': '/'

          }

      })

  );

  app.use(

      '/api',

      proxy.createProxyMiddleware(

        {

          target: 'https://quicklyweb.cn',

          changeOrigin: true,

          pathRewrite: {

            '^/api': '/'

          }

      })

  );

};

```

- 注意:文件名称一定要是 `setupProxy.js`  因为只有这样,项目在启动的时候,才能自动加载!

- 到此,当访问 /mock/**  或者 /api/** 时就能实现代理功能 (只能本地代理,线上环境代理无效)

### 六、后端解决请求跨域问题

> 当实现本地代理后,本地在进行开发时,能够解决前端请求后端接口跨域问题,但当部署到服务器时,本地代理并不会生效,所以,还需要后端解决跨域问题!

**后端解决跨域的常见几种方式**

#### 1、Java过滤器进行过滤

- 允许整个项目跨域访问,可设置过滤器

```java

@WebFilter("/*")

public class SimpleCORSFilter implements Filter{ 


    @Override 

    public void doFilter(ServletRequest req, ServletResponse res, 

            FilterChain chain) throws IOException, ServletException { 

            HttpServletResponse response = (HttpServletResponse) res; 

            response.setHeader("Access-Control-Allow-Origin", "*"); 

            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 

            response.setHeader("Access-Control-Max-Age", "3600"); 

            response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); 

            chain.doFilter(req, res); 


    } 

}

```

- 允许单个方法跨域,可这样设置

```java

response.setHeader("Access-Control-Allow-Origin", "*"); 

response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 

response.setHeader("Access-Control-Max-Age", "3600"); 

response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

```

#### 2、Java后端配置同源Cors(推荐)

- 在 `SpringBoot2.0 ` 上的跨域 用以下代码配置 即可完美解决你的前后端跨域请求问题

```java

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

/**

* 实现基本的跨域请求

* @author 刘路生

*/

@Configuration

public class CorsConfig {

    @Bean

    public CorsFilter corsFilter() {

        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        final CorsConfiguration corsConfiguration = new CorsConfiguration();

        /*是否允许请求带有验证信息*/

        corsConfiguration.setAllowCredentials(true);

        /*允许访问的客户端域名*/

        corsConfiguration.addAllowedOrigin("*");

        /*允许服务端访问的客户端请求头*/

        corsConfiguration.addAllowedHeader("*");

        /*允许访问的方法名,GET POST等*/

        corsConfiguration.addAllowedMethod("*");

        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);

    }

}

```

#### 3、使用SpringCloud网关

```xml-dtd

服务网关(zuul)又称路由中心,用来统一访问所有api接口,维护服务。

Spring Cloud Zuul通过与Spring Cloud Eureka的整合,实现了对服务实例的自动化维护,所以在使用服务路由配置的时候,我们不需要向传统路由配置方式那样去指定具体的服务实例地址,只需要通过Ant模式配置文件参数即可

```

#### 4、使用nginx做转发

- 假设现在有两个网站想互相访问接口 在`http://a.com:81/A`中想访问 `http://b.com:81/B` 那么进行如下配置即可!然后通过访问 `www.my.com/A` 里面即可访问 `www.my.com/B`

```nginx

server {

        listen      80;

        server_name  www.my.com;

        location /A {

            proxy_pass  http://a.com:81/A;

            index  index.html index.htm;

        }

        location /B {

            proxy_pass  http://b.com:81/B;

            index  index.html index.htm;

        }

    }

```

> 以上方法都可解决跨域问题,但推荐使用同源Cors方法

### 七、React 项目部署后,刷新页面报404错误

> 本地开发React项目时,本地能正常加载路由(使用的是BrowserRouter)并且刷新页面也没问题,但将React项目打包后,扔到Tomcat服务器上,虽然能正常访问,在页面内也能正常跳转路由,但当点击刷新页面时,却出现 404 找不到页面 !

#### 1、404 原因

```

之所以在浏览器内可以由首页跳转到其他路由地址,是因为这是由前端自行渲染的,我们在React-Router中定义了对应的路由,脚本并没有刷新网页访问后台,而是JS动态更改了location。

当我们刷新时,浏览器首先是访问的后台地址,然后返回的页面内加载React代码,最后在浏览器内执行;也就是说如果刷新时报404,是因为我们后台并没有针对这个路由给出返回的HTML内容,更谈不上执行React-Router了。

```

#### 2、解决办法(两种)

- 使用 `HashRouter` 作为React的路由,这样不管你如何刷新页面,所有的请求都会定位到index.html这一个页面,并不会访问后台,所以也不会报404错误!

- 在  `tomcat服务器` 的  `config/web.xml  `文件中,加入如下配置,使之404后跳转到 index.html 页面,剩下的就会由React-Router来进行路径跳转。

```xml

<web-app>

    <error-page>

        <error-code>404</error-code>

        <location>/index.html</location>

    </error-page>

</web-app>

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。