【发布时间】:2022-10-20 19:57:54
【问题描述】:
我正在尝试保护 API 路由,并且在不同页面的客户端和服务器端调用此 API 路由。
在test 页面上,它返回401 error。
在test2 页面上,它很好地返回了内容。
我猜当我在getServerSideProps 中发送http 请求时它不会通过session。
我的问题是,如何保护客户端和服务器端使用的 API 路由?
/pages/test
import React from 'react';
import axios from 'axios';
import { getSession } from 'next-auth/react';
const Test = (props) => {
return <div>test</div>;
};
export const getServerSideProps = async (context) => {
// it returns session data
const session = await getSession(context);
// it returns error
const res = await axios.get('/api/secret');
return {
props: {
session,
secret: res.data,
},
};
};
export default Test;
/pages/test2
import React, { useEffect } from 'react';
import axios from 'axios';
import { useSession, getSession } from 'next-auth/react';
const Test = (props) => {
const { data: session } = useSession();
useEffect(() => {
const fetchData = async () => {
const res = await axios.get('/api/secret');
console.log(res.data);
};
fetchData();
}, [session]);
return <div>test</div>;
};
export default Test;
/pages/api/secret
import { getSession } from 'next-auth/react';
const handler = (req, res) => {
const { method } = req;
switch (method) {
case 'GET':
return getSomething(req, res);
default:
return res.status(405).json('Method not allowed');
}
};
const getSomething = async (req, res) => {
const session = await getSession({ req });
console.log(session);
if (session) {
res.send({
content: 'Welcome to the secret page',
});
} else {
res.status(401).send({
err: 'You need to be signed in.',
});
}
};
export default handler;
【问题讨论】:
-
我不知道这是否是您的具体问题,但您的 API 路由处理程序需要是
async -
@Ben 感谢您告诉我!
标签: javascript next.js next-auth