我的前端在 localhost:3000 上运行,后端在 localhost:4000 上运行,在从前端发出登录请求后,我通过响应标头接收到我的 jwt 字符串,如下面的屏幕截图所示
但是问题是,现在当我发出更多的 api 请求时,我的服务器端没有收到这个
req.cookies
打印 undefined
这是我的代码 服务器端
main.ts
export class App {
private readonly app: Application;
constructor(
private readonly port: string | number = process.env.SERVER_PORT || 3000
) {
this.app = express();
this.middleWare();
this.routes();
// Connect to MongoDB
}
listen(): void {
this.app.listen(this.port);
}
private middleWare(): void {
this.app.use((req, res, next) => {
res.set("Access-Control-Allow-Origin", "http://localhost:3000");
res.set("Access-Control-Allow-Credentials", "true");
next()
});
this.app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
this.app.use(express.json());
}
private routes(): void {
this.app.use("/auth", authRoutes);
}
}
控制器.ts
export const signUser = async (req: Request, res: Response) => {
try {
const { existingUser, token } = await loginUser(req.body.data);
return res
.cookie("access_token", token, {
maxAge: 3600,
httpOnly: true,
secure: true,
sameSite: "none",
})
.status(Code.OK)
.send(
new HttpResponse(Code.OK, Status.OK, "Account Logged In.", {
existingUser,
})
);
} catch (error: any) {
console.error(error);
return res
.status(Code.INTERNAL_SERVER_ERROR)
.send(
new HttpResponse(
Code.INTERNAL_SERVER_ERROR,
Status.INTERNAL_SERVER_ERROR,
"An error occurred"
)
);
}
};
客户端 axios-实例-setup.ts
interface postValue<T> {
[key: string]: T;
}
export interface AxiosError<T = any> extends Error {
config: AxiosRequestConfig;
code?: string;
request?: XMLHttpRequest;
response?: AxiosResponse<T>;
isAxiosError: boolean;
toJSON: () => object;
}
class Api {
private axiosInstance: AxiosInstance;
constructor(baseURL: string) {
this.axiosInstance = axios.create({ baseURL });
}
public async post<T>(url: string, data: T): Promise<any> {
try {
const config = {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Credentials": "true"
},
withCredentials: true,
credentials: "include"
};
const res: AxiosResponse<any> = await this.axiosInstance.post(
url,
data,
config
);
return res.data;
} catch (error) {
// Handle errors
throw error;
}
}
const API = new Api("http://localhost:4000/");
export default API;
然后打它
const response = await API.post("/details", {
data: values,
});