React应用抛出axios_1.default.post不是函数错误

ep6jt1vc  于 2023-10-18  发布在  iOS
关注(0)|答案(3)|浏览(160)

我正在使用TypeScript开发React应用程序。我有以下简单的post方法:

import React, { useState } from 'react';
import axios from 'axios';

await axios.post('api/account/register', {
    FirstName: formData.firstName,
    LastName: formData.lastName,
    Username: formData.email,
    Password: formData.password,
    IsLocked: true,
    Role: 'Admin',
});

下面是js文件中的相应代码:

const axios_1 = __importDefault(require("axios"));
const react_1 = __importStar(require("react"));

yield axios_1.default.post('api/account/register', {
    FirstName: formData.firstName,
    LastName: formData.lastName,
    Username: formData.email,
    Password: formData.password,
    IsLocked: true,
    Role: 'Admin',
});

它抛出这个异常:axios_1.default.post不是函数错误。我安装了最新版本的Axios。

下面是ts.config文件:

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "jsx": "react",
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "es6",
    
  }
}

dependencies inside package.json:

"dependencies": {
    //other packages   
    "axios": "1.4.0"
  },

在这里你可以找到几乎所有的项目文件:
https://github.com/erkaner/reactapp-peeraid
我已经检查了一些其他的帖子,但无法找到解决这个问题的方法。有什么需要帮忙的吗?

jvlzgdj9

jvlzgdj91#

经过广泛的测试和调试,并前往不同的来源,以找出有关的问题,问题实际上是与create-react-app。本质上,axios为浏览器提供了一个commonjs模块,而create-react-app的webpack配置似乎没有正确处理它。This问题帮助我确认了这一点。
我做了什么?
我进入Register.js文件,并为axios__1添加了一个console.log,以找出它是-

{
  default: "/static/media/axios.77dc18bde70a91f68d85.cjs"
}

这没有任何意义,我看到扩展名是.cjs,也发现,如果我删除所有的.js文件从项目,它的工作!.为什么?所有文件都是es模块,webpack(来自Register.js源)似乎将axios导入为es模块-

Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));

这里看到__esModule被设置为true,所以它会尝试像这样导入它。现在,正如开始时提到的,这是create-react-app的错误,因为webpack配置不正确,所以请继续阅读。

那么,如何修复呢?

检查create-react-app的webpack配置,以确保babel正确转换并导入代码。我们可以使用cracoreact-app-rewired。我决定用react-app-rewired-
1.使用npm i -D react-app-rewired安装react-app-rewired
1.在项目的根目录下创建一个文件config-overrides.js,然后用下面的代码片段填充它:

const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');

const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';

module.exports = function override(config, webpackEnv) {
  console.log('overriding webpack config...');

  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';
  const loaders = config.module.rules[1].oneOf;

  loaders.splice(loaders.length - 1, 0, {
    test: /\.(js|mjs|cjs)$/,
    exclude: /@babel(?:\/|\\{1,2})runtime/,
    loader: require.resolve('babel-loader'),
    options: {
      babelrc: false,
      configFile: false,
      compact: false,
      presets: [
        [
          require.resolve('babel-preset-react-app/dependencies'),
          { helpers: true },
        ],
      ],
      cacheDirectory: true,
      // See #6846 for context on why cacheCompression is disabled
      cacheCompression: false,
      // @remove-on-eject-begin
      cacheIdentifier: getCacheIdentifier(
        isEnvProduction
          ? 'production'
          : isEnvDevelopment && 'development',
        [
          'babel-plugin-named-asset-import',
          'babel-preset-react-app',
          'react-dev-utils',
          'react-scripts',
        ]
      ),
      // @remove-on-eject-end
      // Babel sourcemaps are needed for debugging into node_modules
      // code.  Without the options below, debuggers like VSCode
      // show incorrect code and set breakpoints on the wrong lines.
      sourceMaps: shouldUseSourceMap,
      inputSourceMap: shouldUseSourceMap,
    },
  });

  return config;
};

1.修改package.json以使用react-app-rewired而不是react-scripts,如下所示-

...

  "scripts": {
    "start": "set HTTPS=true&&react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },

...

就这样,问题就解决了。

tf7tbtn2

tf7tbtn22#

我认为问题来自于config文件,因此您所需要的只是确保启用名为esModuleInterop的功能

{
  "compilerOptions": {
    "esModuleInterop": true,
    // Other options...
  }
}

此选项有助于导入CommonJS模块,其中包括axios等库
有关更多信息,请查看文档中的part

v440hwme

v440hwme3#

我认为问题在于import语句以及如何在TypeScript代码中使用axiosaxios库可以通过以下方式导入和使用:

import React, { useState } from 'react';
import axios from 'axios';

const YourComponent: React.FC = () => {
  const formData = {
    firstName: 'John',
    lastName: 'Doe',
    email: '[email protected]',
    password: 'securepassword',
  };

  const postData = async () => {
    try {
      await axios.post('api/account/register', {
        FirstName: formData.firstName,
        LastName: formData.lastName,
        Username: formData.email,
        Password: formData.password,
        IsLocked: true,
        Role: 'Admin',
      });
      console.log('Post request successful');
    } catch (error) {
      console.error('Error in post request:', error);
    }
  };

相关问题