作为我正在做的项目的一部分,我用 Java 编写了一个 Spring 框架应用程序服务器。 我现在想使用 JavaScript 使用 webpack 为其编写一个客户端。 在我的一个文件中,我使用 POST 方法调用 fetch,但由于某种原因,它被调用两次,并且我的服务器抛出异常(因为它尝试将具有相同键的相同对象放入数据库中) 我认为这与 CORS 有关,因此我从我在该网站上找到的源添加了一个 WebConfig 文件到我的服务器。 但不幸的是,它仍然发生,我不知道为什么。

我的 js 文件与 fetch:

const button = document.getElementById('register'); 
const url = "http://localhost:8083/playground/users"; 
let form; 
 
button.addEventListener("click", async () => { 
  form = { 
    email: document.getElementById("email").value, 
    username: document.getElementById("username").value, 
    avatar: document.getElementById("avatar").value, 
    role: "Guest" 
  }; 
 
  const response = await fetch(url, { 
            method: "POST", 
            mode: "cors", 
            headers: { 
              "Content-Type": "application/json", 
            }, 
            body: JSON.stringify(form), 
          }); 
 
  const resultJson = await response.json(); 
  console.log(resultJson); 
  //location.href='./confirm.html'; 
}); 

webpack.config.js:

const HtmlWebpackPlugin = require('html-webpack-plugin'); 
const path = require('path'); 
const JS_JSX_PATTERN = /\.jsx?$/; 
 
module.exports = { 
  entry: './src/js/index.js', 
  output: { 
    path: __dirname, 
    filename: 'bundle.js' 
  }, 
  plugins: [ 
    new HtmlWebpackPlugin({ 
      filename: 'index.html', 
      template: 'src/index.html' 
    }), 
    new HtmlWebpackPlugin({ 
      filename: 'confirm.html', 
      template: 'src/confirm.html', 
      chunks: [] 
    }) 
  ], 
  module: { 
    loaders: [ 
      { 
        test: JS_JSX_PATTERN, 
        exclude: /node_modules/, 
        loader: 'babel-loader', 
        query: { 
          presets: ['react', 'es2015', 'stage-1'] 
        } 
      } 
    ] 
  }, 
  resolve: { 
    extensions: ['', '.js', '.jsx'] 
  }, 
  devServer: { 
    historyApiFallback: true, 
    contentBase: './', 
    watchOptions: { 
      aggregateTimeout: 300, 
      poll: 1000 
    } 
  } 
}; 

调用 fetch 的结果使其被调用两次,如下所示:

我在这里做错了什么?

请您参考如下方法:

这可能是由于包路径不正确,请尝试使用path.resolve(“您的输出目录”)

.... 
module.exports = { 
  entry: './src/js/index.js', 
  output: { 
    path: path.resolve(__dirname), 
    filename: 'bundle.js' 
  }, 
... 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!