部署Ant-Design-Pro

问题描述

在这种环境下,我相对较新。我将“ Ant design pro 4”与React和Typescript一起用于新项目。

该对象在开发,测试或测试中完美地调用了api。 但是一旦我运行“ npm run build”进行部署,api calls就会得到这个response

我正在Ant-Design-Pro documentation之后的两个不同的服务器(ngnix和express)中运行部署。只是为了确保它的配置不是错误响应的根源。但是在两种情况下,我都会得到相同的错误响应。

我对ngnix服务器的配置是:

server {
    listen 5000;
    # gzip config
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 9;
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-PHP image/jpeg image/gif image/png;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";

    root <location of the generated folder dist>;

    location / {
        # 用于配合 browserHistory使用
        try_files $uri $uri/ /index.html;

        # 如果有资源,建议使用 https + http2,配合按需加载可以获得更好的体验
        # rewrite ^/(.*)$ https://preview.pro.ant.design/$1 permanent;

    }
    location /api {
        proxy_pass <ip of my API>;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_set_header   Host              $http_host;
        proxy_set_header   X-Real-IP         $remote_addr;
    }
}

我对快递服务器的配置是:

const express = require('express')
const app = express()
const port = 3000
var path = require('path')

app.use(express.static(path.join(__dirname,'build')));

app.get('/*',function (req,res) {
  res.sendFile(path.join(__dirname,'build','index.html'));
});

app.listen(port,() => {
  console.log(`Example app listening at http://localhost:${port}`)
})

我的config.ts是:

// https://umijs.org/config/
import { defineConfig,utils } from 'umi';
import defaultSettings from './defaultSettings';
import proxy from './proxy'; 
import webpackPlugin from './plugin.config';
// const { winPath } = utils; // preview.pro.ant.design only do not use in your production ;
// preview.pro.ant.design 专用环境变量,请不要在你的项目中使用它。

const { REACT_APP_ENV,GA_KEY } = process.env;
const api = 'http://xxx.xxx.1.12';//api ip address

export default defineConfig({
  history: { type: 'hash' },// 认是 browser
  hash: true,antd: {},analytics: GA_KEY
   ? {
      ga: GA_KEY,}
   : false,dva: {
   hmr: true,},locale: {
    //default: 'zh-CN',default: 'en_US',// default true,when it is true,will use `navigator.language` overwrite default
    baseNavigator: true,dynamicImport: {
   loading: '@/components/PageLoading/index',targets: {
   ie: 11,// umi routes: https://umijs.org/docs/routing
  routes: [
   {
    <my routes>
   }
 ],// Theme for antd: https://ant.design/docs/react/customize-theme-cn
 theme: {
   // ...darkTheme,'primary-color': defaultSettings.primaryColor,define: {
   REACT_APP_ENV: REACT_APP_ENV || '',ignoreMomentLocale: true,lessLoader: {
   javascriptEnabled: true,cssLoader: {
   modules: {
     getLocalIdent: (
       context: {
         resourcePath: string;
       },_: string,localName: string,) => {
      if (
         context.resourcePath.includes('node_modules') ||
         context.resourcePath.includes('ant.design.pro.less') ||
         context.resourcePath.includes('global.less')
       ) {
         return localName;
       }

    // const match = context.resourcePath.match(/src(.*)/);

    // if (match && match[1]) {
    //   const antdProPath = match[1].replace('.less','');
    //   const arr = winPath(antdProPath)
    //     .split('/')
    //     .map((a: string) => a.replace(/([A-Z])/g,'-$1'))
    //     .map((a: string) => a.toLowerCase());
    //   return `antd-pro${arr.join('-')}-${localName}`.replace(/--/g,'-');
    // }

    return localName;
  },manifest: {
   basePath: '/',proxy:  proxy: {
'/countries': {
  target: `${api}/admin/countries`,changeOrigin: true,pathRewrite: { '^/countries': '' },chainWebpack: webpackPlugin,});

我觉得这是'umi build'制作过程中的一个问题,我试图将自己附加到文档上。有什么建议吗?

解决方法

我一直在遇到同样的问题。 我打电话就像

request('/api/login/account',{
  method: 'POST',data: params,});

并且在非生产环境时有效,因为域名以/config/proxy.ts设置为前缀,如下所示。

  dev: {
    '/api/': {
      target: 'https://localhost:44357',secure: false,changeOrigin: false,pathRewrite: { '^': '' },},

但是proxy.ts在生产环境中不可用。因此,我找到了两种在生产环境中替换proxy.ts的方法。

  1. 使用umi-request的扩展。
  2. 使用umi-request的拦截器。

要使用扩展,我必须将请求源从“ @ / utils / request”更改为“ umi-request”,如下所示。

import request from '@/utils/request'; // New
// import request from 'umi-request'; // Old

并且必须在/src/utils/request.ts中进行如下扩展。

const request = extend({
  prefix: 'https://localhost:44357',// Prefix this to every API call
  errorHandler,// 默认错误处理
  credentials: 'include',// 默认请求是否带上cookie
});

但是,更换许多进口产品对我来说很难。因此,我使用拦截器在URL前面添加了前缀。

当当前环境为生产环境时,我启用了拦截器。但是如果我也检查开发环境并使用另一个URL进行开发,proxy.ts可能就没用了。

// /src/global.tsx

if (process.env.NODE_ENV === 'production') {
  request.interceptors.request.use((url,options) => {
    return {
      url: `https://localhost:44357${url}`,options: { ...options,interceptors: true },};
  });
}
,

正如@doctorgu所述,拦截器是解决此问题的好方法。 以下在src / global.tsx中为我工作了

// https://github.com/umijs/umi-request
request.interceptors.request.use(
  (url,options) => {
        return {
      url: `${URL}${url}`,};
  },{ global: true }
);

.env文件中定义URL的地方

url=http://localhost:8000
PORT=8000

在config.ts中:

const { REACT_APP_ENV,PORT,url} = process.env;

export default defineConfig({
 define: {
    REACT_APP_ENV: REACT_APP_ENV || '',PORT: PORT || 8000,URL: url || ''
  },...
})