这是我的login.js 文件,它负责客户端登录功能。当我在邮递员中点击 api 端点并成功获取 jwt 时,我的后端代码工作正常,这一点很明显。
import axios from 'axios';
export const login = async (email, password) => {
try {
const res = await axios({
method: 'POST',
url: '/api/v1/users/login',
data: {
email,
password,
},
});
if (res.data.status === 'success') {
showAlert('success', 'Logged in successfully!');
window.setTimeout(() => {
location.assign('/');
}, 1500);
}
} catch (err) {
showAlert('error', err.response.data.message);
}
};
这是我的哈巴狗模板,它负责渲染所需的 html 表单
extends base
block content
main.main
.login-form
h2.heading-secondary.ma-bt-lg Log into your account
form.form.form--login
.form__group
label.form__label(for='email') Email address
input#email.form__input(type='email', name='email', placeholder='[email protected]', required)
.form__group.ma-bt-md
label.form__label(for='password') Password
input#password.form__input(type='password', name='password', placeholder='••••••••', required, minlength='8')
.form__group
button.btn.btn--green(type='submit') Login
这是我的 index.js,我在其中添加事件监听器
const loginForm = document.querySelector('.form--login');
if (loginForm)
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
login(email, password);
});
问题是,当我进入本地主机并检查控制台的网络选项卡时,当我提交表单(点击登录按钮)而不是所需的 POST 请求时,会触发 GET 请求,并且电子邮件和密码正在被触发附加到 url 作为查询参数,即使之前没有发生过。
我尝试使用 chatgpt 来实现此目的,但他一直循环回到控制台日志记录的相同调试方法,而我实际上也这样做了。我控制台记录了
console.log(loginForm);
但控制台上没有出现任何内容,我认为可能是包裹捆绑程序引起了这个问题,所以我卸载并重新安装了它,但无济于事。我的终端中也出现此错误
在此服务器上找不到 /bundle.js.map!
即使它与 /bundle.js 位于同一目录中
这是我的基本哈巴狗模板,用于附加上下文
doctype html
html
head
block head
meta(charset='UTF-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
link(rel='stylesheet' href='/css/style.css')
link(rel='shortcut icon' type='image/png' href='/img/favicon.png')
link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:300,300i,700')
title Natours | #{title}
body(data-alert=`${alert ? alert : ''}`)
// HEADER
include _header
// CONTENT
block content
h1 This is a placeholder heading
// FOOTER
include _footer
script(src='https://js.stripe.com/v3/')
script(src='/js/bundle.js')
您是否尝试过使用 fetch api 来处理相同的请求?