如何修复此打字稿错误:类型“字符串”不可分配给类型“RequestCredentials |”未定义'

问题描述 投票:0回答:1

我是一个在 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);
  }
};
reactjs typescript vite
1个回答
0
投票

您可以在

: RequestInit
之后添加
const option
,如下所示:

const option: RequestInit = {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({}),
  credentials: 'include',
};
© www.soinside.com 2019 - 2024. All rights reserved.