【问题标题】:Why is the response returning 204为什么响应返回 204
【发布时间】:2022-01-03 11:29:44
【问题描述】:

当我将商品添加到购物车时,我将购物车作为响应发回。没问题。这些代码在区域设置(我的电脑)中工作,返回响应 200。 但是当我将项目发送到托管时。当我将商品添加到购物车时,响应 204(Null) 。我没有解决这个问题。

                BACKEND(.Net Core 3.1 ASPNET Web Api)

               FrontEnd 
import { message } from "antd";

export type ApiSuccessResponse<T> = {
    ok: true;
    data: T;
};

export type ApiErrorResponse = {
    ok: false;
    status: number;
    message: string;
};

export type ApiResponse<T> = ApiSuccessResponse<T> | ApiErrorResponse;

export type RequestMethod = "DELETE" | "GET" | "PATCH" | "POST" | "PUT";

export async function request<T>(
    uri: string,
    method?: RequestMethod,
    body?: any
): Promise<ApiResponse<T>> {
    let token = localStorage.getItem("token");
     
    const response = await fetch(`/api/${uri}`, {
        method: method || "GET",
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            Authorization: "Bearer " + (token || ""),
        },
        body: body ? JSON.stringify(body) : undefined,
    });
    if (!response.ok) {
        if (response.status === 401) {
            localStorage.clear();
            window.location.reload();
        } else if (response.status === 500) {
            const text = await response.text();
            if (text && text.length) {
                message.error(JSON.parse(text).message);
            }
        }
        return {
            ok: false,
            status: response.status,
            message: response.statusText,
        };
    }

    const text = await response.text();

    if (text && text.length > 0) {
        const data = JSON.parse(text);
        return { ok: true, data: data as T };
    }

    return { ok: true, data: null! };
}
```

【问题讨论】:

    标签: c# api asp.net-core


    【解决方案1】:

    204 表示端点成功但没有内容。 据我所知,您返回的是空值。请解构您的最后一行并等待结果,如下所示:

    var authServiceUnit = await CreateAuthServiceUnitAsync(_masterServiceUnit);
    var cartDto = await authServiceUnit.CarService.GetCartAsync(CarId,KullaniciId, UserType);
    return cartDto; // set here a breakpoint
    
    

    cartDto 应该为空。

    【讨论】:

    • 好吧,我知道,cartDto 返回 null 但 CartDTo 从我的语言环境(我的计算机)返回响应 200,但是当我使用 filezilla 进行主机环更新时返回 204 :( 代码在主机上工作
    • 所以它返回正确的代码。如果您想发送 200 代码,您有两种选择。 return OK(cartDto)if(cartDto == default) return new CartDto()。结果不同的原因可能取决于您的数据库,如果它们没有相同的记录。
    • Heaxyh,你知道是对的 :) 感谢我的语言环境连接的托管数据库,我看到了错误。代码是正确的,但来自数据库的错误
    猜你喜欢
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2014-01-28
    • 2018-10-23
    • 2016-09-04
    相关资源
    最近更新 更多