gpt4 book ai didi

javascript - 通过 javascript 使用自定义 header 检查凭据后加载 html 页面

转载 作者:行者123 更新时间:2023-12-03 00:40:55 24 4
gpt4 key购买 nike

我是 JavaScript 和 Web 编程新手。我正在尝试为我使用 node.js 编写的产品构建一个配置网页。出于这个原因,我使用express作为后端,并在前端使用一些html、css和javascript。场景是这样的:

  1. 客户打开登录页面,要求他输入用户名和密码。
  2. 按下登录按钮后,用户名和密码的值将使用 post 请求发送到“/login”地址,如果凭据正确,则会将 token 作为响应发送回客户端并将设置在客户端本地存储中。

  3. 客户端自动向“/config”地址发送 GET 请求,其中会出现一个 protected html 页面,用于验证加载时的 token 并显示一些字段。

问题是当第二阶段完成时,客户端向/config 发送 GET 请求,但响应未在页面中加载,但我可以在 google chrome > 开发人员工具 > 网络部分中看到响应页面。

我使用 axios 发送请求并使用 express 作为后端 Web 服务器。

这是我使用express的后端代码:

const config = require('config');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const jwt = require('jsonwebtoken');
const port = 3333;
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'webconfig', 'login.html'))
});

app.get('/config', verifyToken,(req, res)=> {
console.log('GET /config data');
res.sendFile(path.join(__dirname, 'webconfig', 'config.html'));
});

app.post('/login', (req, res) => {
console.log('POST /login');
const {body} = req;
if (body.username === config.web.username && body.password === config.web.password) {
const user = {
id: 1,
username: 'admin'
};
jwt.sign({user}, jwt_secret, {expiresIn: '3000s'}, (err, token) => {
console.log('Token sent to client');
res.send({
token: token,
});
});
} else {
console.log('User pass mismatch');
res.redirect('/')
}
});

这是我在客户端的 js,它在按钮单击时触发:

const username = document.getElementById('username');
const password = document.getElementById('password');

async function login() {
axios.post('/login', {
"username": username.value,
"password": password.value
})
.then(function(res) {
window.localStorage.setItem('token', res.data.token);
let token = window.localStorage.getItem('token');
if (token !== 'undefined'){
axios.get('/config',{headers:{Authorization:'Bearer ' + token }})
} else {
window.location.href = '/'
}
})
.catch(function(err) {
console.log(err)
});
}
}

verifyToken函数是一个中间件,它验证 token 并调用下一个函数。

毕竟我提到过我是网络开发新手,因此非常感谢您的帮助。

最佳答案

问题是您正在使用 axios .

Axios 制作 XMLHttpRequests 。所以,当您使用axios.get时,页面未加载 html响应,它只是获取它并将其存储在响应对象中。

加载另一个页面window.location建议这样做,但由于您还想发送 header ,这使得它变得很困难。

引用这个,它可能正是您正在寻找的。

Adding http headers to window.location.href in Angular app

关于javascript - 通过 javascript 使用自定义 header 检查凭据后加载 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com