简体   繁体   English

部署 Ant-Design-Pro 后不调用 api

[英]not calling api after deployment Ant-Design-Pro

I'm relatively new in this environment.我在这个环境中相对较新。 I use "Ant design pro 4" with React and Typescript for a new project.我将“Ant design pro 4”与 React 和 Typescript 一起用于新项目。

The proyect calls the api perfectly in dev, pre, or test. proyect 在 dev、pre 或 test 中完美调用 api。 But once I run 'npm run build' to deploy, the api calls are getting this response .但是一旦我运行“npm run build”进行部署, api 调用就会得到这个响应

I'm running the deployment in two different servers(ngnix and express) following the Ant-Design-Pro documentation .我正在按照Ant-Design-Pro 文档在两个不同的服务器(ngnix 和 express)中运行部署。 just to make sure that the configuration of it wasn't the root of the wrong response.只是为了确保它的配置不是错误响应的根源。 But in both cases I'm getting the same wrong response.但在这两种情况下,我都得到了同样的错误回应。

my configuration for the ngnix server is:我对 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;
    }
}

my configuration for the express server is:我对快递服务器的配置是:

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}`)
})

my config.ts is:我的 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,
  });

I have the feeling is a problem in the building process which is made by 'umi build', I tried to attach my self to the documentation.我感觉是'umi build'在构建过程中出现了问题,我试图将自己附加到文档中。 Any suggestion?有什么建议吗?

I've been suffering with same problem.我一直在遭受同样的问题。 I was calling like我在打电话

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

And It is valid when environment is not production because domain name was prefixed by /config/proxy.ts setting as below.并且当环境不是生产环境时它是有效的,因为域名以 /config/proxy.ts 设置为前缀,如下所示。

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

But proxy.ts is not available in production environment.但是 proxy.ts 在生产环境中不可用。 So I found 2 ways to replace proxy.ts in production.所以我找到了两种在生产中替换 proxy.ts 的方法。

  1. Use extend of umi-request.使用 umi-request 的扩展。
  2. Use interceptors of umi-request.使用 umi-request 的拦截器。

To use extend, I have to change request source from '@/utils/request' to 'umi-request' as following.要使用 extend,我必须将请求源从 '@/utils/request' 更改为 'umi-request',如下所示。

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

And have to extend in /src/utils/request.ts as following.并且必须在 /src/utils/request.ts 中扩展如下。

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

But replacing many import was tough for me.但是替换许多进口对我来说很难。 So I used interceptors to prefix URL as following.所以我使用拦截器为 URL 添加前缀,如下所示。

I enabled interceptors when current environment is production.我在当前环境为生产环境时启用了拦截器。 But proxy.ts can be useless if I check for development environment also and use another URL for development.但是如果我也检查开发环境并使用另一个 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 },
    };
  });
}

As @doctorgu mentioned, interceptors are a good way to solve this.正如@doctorgu 提到的,拦截器是解决这个问题的好方法。 Following worked for me in src/global.tsx以下在 src/global.tsx 中为我工作

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

where URL is defined in.env file其中 URL 在 .env 文件中定义

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

in 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 || ''
  },
...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM