背景
需要钉钉扫码登录功能
钉钉文档
open.dingtalk.com/document/or…
遇到的问题,跨域问题
页面地址:http://xxx-dev.com/api/cms
配置参数 redirect_uri 属性值: http://yyy-dev-api.com/api/cms
后续解决方法 nginx 将 xxx-dev.com/api/cms 转发到 yyy-dev-api.com/api/cms 上解决了问题
实现代码案例
import { getWebpagePrefix } from "@/utils/tools";
import { message } from "antd";
import { useEffect } from "react";
import { history, useDispatch } from "umi";
export default function DingDingLogin() {
const dispatch = useDispatch();
useEffect(() => {
console.log(getWebpagePrefix());
window.DTFrameLogin(
{
id: "self_defined_element",
width: 300,
height: 300,
},
{
redirect_uri: encodeURIComponent(
`${getWebpagePrefix()}/api/cms/v1/user/dinding/auth`,
),
client_id: "xxxx",
scope: "openid",
response_type: "code",
state: "",
prompt: "consent",
},
(loginResult: any) => {
const { redirectUrl, authCode, state } = loginResult;
fetch(redirectUrl, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res: any) => res.json())
.then((res: any) => {
console.log("res", res);
if (res.code === 200) {
let data = res?.data || {};
dispatch({
type: "account/changeLoginInfo",
payload: { data: { ...data } },
});
history.push("/");
} else {
message.error(res.msg);
}
});
message.success("登录成功");
},
(errorMsg: any) => {
// 这里一般需要展示登录失败的具体原因,可以使用toast等轻提示
console.error(`errorMsg of errorCbk: ${errorMsg}`);
message.error(`登录失败 errorMsg of errorCbk: ${errorMsg}`);
},
);
}, []);
return <div id="self_defined_element"></div>;
}