【问题标题】:JavaScript Fetch with method "POST" is called twice使用方法“POST”的 JavaScript Fetch 被调用两次
【发布时间】:2018-12-08 16:16:21
【问题描述】:

作为我正在做的一个项目的一部分,我用 Java 编写了一个 Spring 框架应用服务器。 我现在想使用 webpack 使用 JavaScript 为它编写一个客户端。 在我的一个文件中,我使用 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 的结果使它被调用了两次,如下所示:

我在这里做错了什么?

【问题讨论】:

  • 你的 HTML 文件的头部是否有一个 src 为 "bundle.js" 的脚本标签?
  • 为什么第一次调用失败,而不是第二次调用?
  • @RandyCasburn 我有一个脚本标签,但它在我的身体里,有关系吗?

标签: javascript java spring post


【解决方案1】:

这可能是由于不正确的捆绑路径尝试使用 path.resolve("your output directory")

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

【讨论】:

  • 你,我的朋友,是个了不起的人。这实际上是我的问题,谢谢。
【解决方案2】:

看起来您正在使用自定义HtmlWebpackPlugin 模板——您是否有一个脚本标记指向./bundle.js 在那个src/index.html 中?

HtmlWebpackPlugin 旨在为您自动添加捆绑脚本。看截图,我猜VM....bundle.jswebpack-dev-server从内存中提供的,第二个bunde.js是你在之前的webpack build本地创建的。

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2021-11-04
    • 2013-12-31
    • 1970-01-01
    • 2014-05-22
    • 2021-06-11
    • 2020-07-16
    • 2014-09-02
    相关资源
    最近更新 更多