我是一个在 Vite 环境中使用 typescript 学习 React 的初学者。我有一个注册函数,它将向服务器发送获取请求以注册用户,我注意到发送回服务器的 cookie 没有记录在网络选项卡(chrome 开发工具)中,我发现我拼错了
credentials
到credential
。当我现在修复它时,它工作得很好。一切都很好,即使出现打字稿错误,应用程序仍在运行,
如何解决选项参数中的此问题错误?: fetch(....ulr, option);`?
Argument of type '{ method: string; headers: { "Content-Type": string; }; body: string; credentials: string; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'credentials' are incompatible.
Type 'string' is not assignable to type 'RequestCredentials | undefined'.
这是我的代码:
import { RegisterProps } from "../pages/Register";
export const register = async (formData: RegisterProps) => {
const API_URI = import.meta.env.VITE_BASE_URL;
//specify the options
const option = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
credentials: "include",
};
//fetch request
const response = await fetch(`${API_URI}/apiv1/auth/register`, option);
//data response form the server
const data = await response.json();
if (!response.ok) {
throw new Error(data.message);
}
};
您可以在
: RequestInit
之后添加 const option
,如下所示:
const option: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
credentials: 'include',
};