我有一個 Next.JS 應用程式,我在其中使用檔案中的代碼實作了 auth0 登錄:
// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();
// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';
export default function Profile() {
const { user, error, isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
return (
user && (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
)
);
}
該代碼正在運行,我可以登錄。當我正確理解時,我的 index.js 現在受到保護。
然后我在 auth0 中添加了一個 API 應用程式。
現在我在 node.js 中創建了一個小服務器:
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const helmet = require("helmet");
const jwt = require("express-jwt");
const jwks = require("jwks-rsa");
const authConfig = require("./auth_config.json");
const app = express();
const port = process.env.API_PORT || 3001;
const appPort = process.env.SERVER_PORT || 3000;
const appOrigin = authConfig.appOrigin || `http://localhost:${appPort}`;
if (!authConfig.domain || !authConfig.audience) {
throw new Error(
"Please make sure that auth__config.json is in place and poplated"
);
}
const jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,
}),
audience: authConfig.audience,
issuer: `http://${authConfig.domain}`,
algorithms: ["RS256"],
});
app.use(morgan("dev"));
app.use(helmet());
app.use(cors({ origin: appOrigin }));
app.use(jwtCheck);
app.get("/api/protected", (reg, res) => {
res.send({
msg: "You called the protected endpoint!",
});
});
app.listen(port, () => console.log(`API server listening on port ${port}`));
我現在的問題是:如何api/protected從 index.js呼叫路徑?
uj5u.com熱心網友回復:
如果我理解正確,您是在問如何在組件內進行 api 呼叫?如果是,下面是一個例子。
import axios from "axios";
const yourfunctionName = async (email, password) => {
try {
const response = await axios.get(`http://localhost:3000/api/protected`, {
data
});
return response.data
} catch (error) {
console.log(error.message);
}
};
uj5u.com熱心網友回復:
看一下示例useFetchUserhook。
此處/api/me僅在用戶登錄時才發送對端點的 HTTP 呼叫。
在示例主頁中,通過呼叫 hook加載用戶:
const { user, loading } = useFetchUser()
你會做類似的事情,但是它會略有不同,因為你不需要有條件地重定向到身體useProtectedInfo或任何你決定稱之為你的鉤子。
該結構將與示例大體相似。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405312.html
標籤:
