使用方法 "POST"的 JavaScript Fetch 被调用两次

标签 javascript java spring post

作为我正在做的项目的一部分,我用 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 的结果使其被调用两次,如下所示: enter image description here

我在这里做错了什么?

最佳答案

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

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

关于使用方法 "POST"的 JavaScript Fetch 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684439/

相关文章:

javascript - $( "#id").val();显示错误结果?

javascript - 计算杠铃获得特定重量所需的重量

javascript - 如何在 Ember 中从表单提交转换路由?

spring - 使用 Spring Social 进行 Twitter 直播

javascript - 我希望 Google Docs 嵌入式 PDF 查看器不显示 "open external"链接

java - Gradle WEB-INF/classes 文件夹

java - 如何使用 jackson 解析可能是字符串并且可能是数组的字段

java - 如何在第二列或特定列中插入 jface TreeViewer?

带有 MySql 和 Maven 的 Spring Data JPA 简单 Web 示例

java - MVC GET Controller ,带有 . PathVariable 中的 [dot] 值