Axios通过Webpack和Babel获取请求

问题描述 投票:0回答:1

我正在使用Webpack和Babel并尝试创建axios GET请求,并且当我使用异步函数包含axios请求时,捆绑过程失败。

如果删除异步功能,则捆绑过程成功。

帮助?

package.json:

"devDependencies": {
"@babel/core": "^7.8.7",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-preset-env": "^1.7.0",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"axios": "^0.19.2",
"babel-polyfill": "^6.26.0"
 }

Webpack.config.js:

  const path = require('path');
  const htmlWebpackPlugin = require('html-webpack-plugin');

  module.exports = {
  entry: ['babel-polyfill', './src/JS/index.js'],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  },

  devServer: {
    contentBase: './dist'
  },

  plugins: [
    new htmlWebpackPlugin({
        filename: 'index.html',
        template: './src/index.html'
    })
  ],

  module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader'
             }
         }
      ]
   }
 };

index.js:

import axios from 'axios';

async function getResults(query) {
    const res = await axios.get(`https://forkify-api.herokuapp.com/api/search?q=${query}`);
    console.log(res);
};

getResults(1)
javascript ajax webpack axios babel
1个回答
0
投票

您需要将async & await transpile转换为将在浏览器中运行的内容。

存在冗余的babel软件包,它们相互干扰。

// package.json

"@babel/core": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"babel-loader": "^8.0.6",
// .babelrs

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry"
      }
    ]
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.