想学着写一个登录的网页,在网上搜了一下,给我一个写好的模板,运行一直报错。
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
<script src="https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<form id="loginForm">
<div>
<label>用户名:</label>
<input type="text" id="username" required>
</div>
<div>
<label>密码:</label>
<input type="password" id="password" required>
</div>
<button type="submit">登录</button>
</form>
<script setup>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// const axios = require('axios');
try {
const response = await axios.post('/api/login', {
username,
password
});
if(response.data.success) {
localStorage.setItem('token', response.data.token);
window.location.href = '/dashboard';
} else {
alert('登录失败: ' + response.data.message);
}
} catch (error) {
console.error('登录错误:', error);
alert('登录请求失败');
}
});
</script>
</body>
</html>
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
// 模拟用户数据库
const users = [
{ id: 1, username: 'admin', password: '123456' }
];
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
// 查找用户
const user = users.find(u =>
u.username === username &&
u.password === password
);
if (user) {
// 生成JWT令牌
const token = jwt.sign(
{ userId: user.id },
'your-secret-key',
{ expiresIn: '1h' }
);
res.json({
success: true,
token,
message: '登录成功'
});
} else {
res.status(401).json({
success: false,
message: '用户名或密码错误'
});
}
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
我在command窗口中npm i express , npm i body-parser, npm i jsonwebtoken
还有npm i axios --save-dev, 然后运行js档案 npm start , 显示服务器运行起来了
但是在网页中打开html后,输入 ID& PW点登录,却提示
"AxiosError: Request failed with status code 404\n at Ye (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:31710)\n at XMLHttpRequest.y (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:36585)\n at e.<anonymous> (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:48581)\n at p (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:3448)\n at Generator.<anonymous> (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:4779)\n at Generator.throw (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:3858)\n at p (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:9996)\n at s (https://fastly.jsdelivr.net/npm/axios/dist/axios.min.js:2:10235)"
是这个引用的URL没有我要的post 方法吗?
原本网上提供的代码引用的URL是CDN.jsdeliver.net,但是一直打不开,我就改成fastly.jsdeliver.net网址引用。