【发布时间】: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
}
}
};
我在这里做错了什么?
【问题讨论】:
-
你的 HTML 文件的头部是否有一个 src 为 "bundle.js" 的脚本标签?
-
为什么第一次调用失败,而不是第二次调用?
-
@RandyCasburn 我有一个脚本标签,但它在我的身体里,有关系吗?
标签: javascript java spring post