Express[Nest.js]-res.cookie()未在Heroku产品中设置
我使用的是Next.js(前端)和Nest.js(后端)框架,我的HTTP Cookies出现了问题。以下代码在通过localhost进行的开发中起作用,但在将代码发布到vercel(Next.js)和Heroku(Nest.js)时不起作用 下面是我的Nest.js设置的一个片段 //梅因酒店Express[Nest.js]-res.cookie()未在Heroku产品中设置,express,heroku,cross-domain,nestjs,httpcookie,Express,Heroku,Cross Domain,Nestjs,Httpcookie,我使用的是Next.js(前端)和Nest.js(后端)框架,我的HTTP Cookies出现了问题。以下代码在通过localhost进行的开发中起作用,但在将代码发布到vercel(Next.js)和Heroku(Nest.js)时不起作用 下面是我的Nest.js设置的一个片段 //梅因酒店 async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: new Lo
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: new LoggerService(),
cors: true,
});
app.use(cookieParser());
app.enableCors({
origin: ["<my-site>"],
credentials: true,
});
...
await app.listen(process.env.PORT || 5000);
}
bootstrap();
下面是我在Next.js中的useAuth组件
import React from "react";
import jwtDecode from "jwt-decode";
import nookies from "nookies";
import { redirect } from "../../services/redirect";
import { GetServerSideProps, NextPage } from "next";
export interface User {
accessToken: string;
email: string;
exp: number;
iat: number;
id: string;
name: string;
roles: Array<string>;
}
const AuthContext = React.createContext<User>(null as unknown as User);
const loginRoute = `/login`;
export const authenticate = (
getServerSidePropsInner: GetServerSideProps = async () => ({ props: {} })
) => {
const getServerSideProps: GetServerSideProps = async ctx => {
const { req, res } = ctx;
if (!req.headers.cookie) {
console.log("no cookie found");
redirect(ctx, loginRoute);
return { props: {} };
}
const { accessToken } = nookies.get(ctx);
console.log(accessToken);
let user = null;
try {
user = {
accessToken,
...(jwtDecode(accessToken as string) as object),
};
} catch (e) {
console.log(e);
redirect(ctx, loginRoute);
}
const result = await getServerSidePropsInner(ctx);
return {
...result,
props: {
user,
//@ts-ignore
...result.props,
},
};
};
return getServerSideProps;
};
export const withAuth = (C: NextPage) => {
const WithAuth = (props: any) => {
const { user, ...appProps } = props;
return (
<AuthContext.Provider value={user}>
<C {...appProps} />
</AuthContext.Provider>
);
};
WithAuth.displayName = `WithAuth(${C.displayName})`;
return WithAuth;
};
export default withAuth;
export const useAuth = (): User => React.useContext(AuthContext);
安装程序使用localhost。它添加了一个http cookie,由next.js应用程序读取。
但是,将my Nest.js应用程序部署到Heroku时,cookie似乎不会发送到下一个应用程序。我尝试为CookieOptions添加不同的值
sameSite: "none",
secure: true,
httpOnly: false,
然而,这也无济于事
非常感谢您的帮助,因为我已经为此奋斗了好几天了
verifyLogin: ({ code, email }: { code: string; email: string }) => {
return axios(`${apiURI}/user/login/verify`, {
method: `POST`,
withCredentials: true,
headers: {
"Content-Type": "application/json",
},
data: {
code: code,
email: email,
},
});
},
sameSite: "none",
secure: true,
httpOnly: false,