最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React app throwing axios_1.default.post is not a function error - Stack Overflow

programmeradmin1浏览0评论

I am working on a React application using TypeScript. I have the following simple post method:

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

Below is the corresponding code from the js file:

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

It throws this exception: axios_1.default.post is not a function error. I have the latest version of axios installed.

Below is the ts.config file:

{
  "pileOnSave": true,
  "pilerOptions": {
    "module": "monjs",
    "jsx": "react",
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "es6",
    
  }
}

dependencies inside package.json:

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

Here you can find almost all project files:

I have checked some other posts but could not find a solution to this problem. Any help?

I am working on a React application using TypeScript. I have the following simple post method:

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

Below is the corresponding code from the js file:

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

It throws this exception: axios_1.default.post is not a function error. I have the latest version of axios installed.

Below is the ts.config file:

{
  "pileOnSave": true,
  "pilerOptions": {
    "module": "monjs",
    "jsx": "react",
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "es6",
    
  }
}

dependencies inside package.json:

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

Here you can find almost all project files:

https://github./erkaner/reactapp-peeraid

I have checked some other posts but could not find a solution to this problem. Any help?

Share Improve this question edited Aug 14, 2023 at 19:00 renakre asked Aug 12, 2023 at 6:39 renakrerenakre 8,3118 gold badges53 silver badges112 bronze badges 12
  • Could you search in the whole project for this term axios_1 using ctrl + shift + f? – Joseph Commented Aug 12, 2023 at 17:41
  • @Joseph I have updated my code. It is in the js file corresponding to the TSX file. – renakre Commented Aug 12, 2023 at 17:59
  • looks like you run built cjs code in a browser env? if so, this doesn't work definitely – tmhao2005 Commented Aug 14, 2023 at 7:35
  • @tmhao2005 can you elaborate more on this? How can I solve this issue? – renakre Commented Aug 14, 2023 at 11:54
  • I think you should provide a minimal reproducible repo so that we know the way you run your app – tmhao2005 Commented Aug 14, 2023 at 12:17
 |  Show 7 more ments

3 Answers 3

Reset to default 11 +500

After testing and debugging extensively, and going to different sources to find out about the issue, the issue actually is with the create-react-app. Essentially, axios provides a monjs module for browser, and the webpack config of the create-react-app doesn't seem to be handling it properly. This issue helped me confirm it.

What did I do?

I went into the Register.js file and added a console.log for axios__1 to find out, that it's -

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

which didn't make any sense, I saw that the extension is .cjs and also found out that if I delete all the .js files from the project, it works!. Why? All the files are es modules and webpack (from the Register.js source) seems to be importing axios as an es module -

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

See here that the __esModule is set to true, so it'll try to import it like so. Now, as mentioned at the start, it's the create-react-app's fault for incorrect webpack config, so read on.

So, how to fix it?

Override the webpack config of the create-react-app to make sure the babel properly transpiles and imports the code. We can make use of craco or react-app-rewired. I decided to go with react-app-rewired -

  1. Install react-app-rewired with npm i -D react-app-rewired.
  2. create a file config-overrides.js at the project root, and fill it up with this code snippet -
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,
      pact: 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. Modify the package.json to use react-app-rewired instead of react-scripts, like so -
...

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

...

And that's it, that'll resolve the issue.

I think the problem es from typescript config file so all you need is to make sure that you enable feature called esModuleInterop

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

This option helps with importing CommonJS modules, which includes libraries like axios

for more info check this part from docs

I think problem es with the import statements and how you're using axios in your TypeScript code. The axios library could be imported and used in the following manner:

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);
    }
  };
发布评论

评论列表(0)

  1. 暂无评论