react ant新开窗口并携带basic auth
在React中,可以使用window.open()方法打开一个新的窗口,并使用基本身份验证(Basic Auth)。
首先,确保你的React应用程序中已经安装了react-router-dom包,以便在新窗口中打开URL。
然后,你可以创建一个函数来处理新窗口的打开请求,并将基本身份验证的凭据添加到URL中。以下是一个示例:
import { useHistory } from 'react-router-dom';
const openNewWindow = () => {
const username = 'your_username';
const password = 'your_password';
const basicAuth = btoa(`${username}:${password}`);
const url = `http://your_domain.com/protected-page`;
const authUrl = `${url}?auth=${basicAuth}`;
window.open(authUrl, '_blank');
}
const MyComponent = () => {
const history = useHistory();
const handleOpenNewWindow = () => {
openNewWindow();
history.push('/'); // 可选:在打开新窗口后,将用户重定向到其他页面
}
return (
<div>
<button onClick={handleOpenNewWindow}>Open New Window</button>
</div>
);
}
export default MyComponent;
在上面的代码中,openNewWindow函数将用户名和密码编码为Base64字符串,并将其添加到URL中。然后,使用window.open()打开一个新窗口并传递URL。你还可以使用history.push()方法将用户重定向到其他页面,这是可选的。
请注意,基本身份验证是一种不安全的身份验证方法,因为凭据会以明文形式传递。因此,建议在使用基本身份验证时仅用于安全性要求较低的应用程序。
原文地址: https://www.cveoy.top/t/topic/i7mT 著作权归作者所有。请勿转载和采集!