我有一个用TypeScrip编写的工作客户端和一个用c#编写的遗留Web服务器.我正在try 将C#代码转换为nodes.js/express.

客户端获取函数:

export async function myFetch(url : String, data : Object | null)  {

    const bodyData = JSON.stringify(data);
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: bodyData
    }
    const fullUrl = serviceBase() + url;
    let res;

    try {
      if (data==null)
        res = await fetch(fullUrl);
      else
        res = await fetch(fullUrl, options);

      if (!res.ok) {
        throw new Error(`HTTP error: ${res.status}`);
      }
      return await res.json();
    }

   catch (error : any) {
      AlertError('Web error',error)
    }
  
  }

这是一个服务器端点的接口(在C#中):

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/GetRidesForDate", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[ServiceKnownType(typeof(List<Ride>))]
IEnumerable<Ride> GetRidesForDate(int date);

使用此选项,GetRidesForDate将返回正确的结果.

在 node /快速try 中,我有:

const app = express ();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.listen(port, () => {
    console.log("Server Listening on PORT:", port);
  });
app.get("/GetRidesForDate/:date", (request: any, response: { json: (arg0: any[]) => void; }) =>
  {
    console.log('getRidesForDate '  + request.params.date);
    getRidesForDate(request,response);
  })

但如果我用以下命令调用客户端FETCH

rides.value = await myFetch("GetRidesForDate",18800);

服务器代码永远不会到达console.log,相反,我得到一个错误:

SyntaxError: Unexpected token '1', "#" is not valid JSON
at JSON.parse (<anonymous>)

这里的1是提取数据的第一个数字.客户端发出400错误(错误请求).

如果我使用浏览器并转到http://localhost:3000/GetRidesForDate/18800,NODE/Express服务器会正确响应.

app.get()的参数应该是什么,才能使这与我的fetch命令一起工作?

推荐答案

问题是FETCH Body JSON.stringify(18800)不是有效的JSON,而解析错误来自服务器JSON Body解析器,因此出现400 Bad request错误(不熟悉c#,所以不知道为什么那里没有错误..).

因此,您需要实际使用有效的JSON:

而不是这样:

const bodyData = JSON.stringify(data);//18800: not valid JSON

使用以下命令:

const bodyData = JSON.stringify({data}); //{"data":18800}: valid JSON

然后通过req.body.data在服务器上访问它.

此外,您还不清楚如何处理这个请求,因为在您的客户端提取代码中,您似乎有两个请求:一个是GET,一个是POST(产生错误),但这两个请求都不应该工作,因为在服务器上,您只有GET ROUTE需要:date个参数,而您似乎只通过POST请求中的BODY发送它.

那么,为什么不总是通过Body发送它,然后如果它是未定义的,则将其设置为某个默认值,然后进行处理.

如果你真的想让这条路由同时使用POST和GET,那么你可以使用app.use("/GetRidesForDate"....,但这似乎没有意义,而且,你需要在url中添加:date参数,而不是使用body,这就是为什么总是使用req.body可能更方便的原因.

一百零二

试试这个:

客户:(用谷歌翻译翻译)

export async function myFetch(url : String, data : Object | null)  {

    const bodyData = JSON.stringify({data});
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: bodyData
    }
    const fullUrl = serviceBase() + url;
    let res;

    try {
        res = await fetch(fullUrl, options);

      if (!res.ok) {
        throw new Error(`HTTP error: ${res.status}`);
      }
      return await res.json();
    }

   catch (error : any) {
      AlertError('Web error',error)
    }
  
  }

服务器:服务器:

// to make both GET and POST work, you could use `app.use("/GetRidesForDate"....`, but there seems to be no purpose for that..
  app.post("/GetRidesForDate", (request: any, response: { json: (arg0: any[]) => void; }) =>
  {
    console.log('getRidesForDate ', request.body.data);
    // if no req.body.data, add some defaults..
    getRidesForDate(request,response);
  })

Csharp相关问答推荐

无法将blob发送到Azure -缺少HTTP标头异常

如何修改中间件或其注册以正确使用作用域服务?

实体框架核心上是否支持使用NPGSQL的字符串聚合?

在FilePath中搜索一个词,并根据First Match从左到右提取文件路径

在此系统上已禁用获取正在运行的脚本.&在ASP.NET Core Web API中

调用Task.Run()与DoSomethingAsync()有什么不同?

Automapper 12.x将GUID映射到字符串

带有列表参数的表达式树

使用switch 类型模式时出现奇怪的编译器行为

有条件地定义预处理器指令常量

System.NotSupportdException:流不支持读取

ReadOnlyMemory访问基础索引的替代方案

未显示详细信息的弹出对话框

数据库操作预计影响1行,但实际影响0行; after _dbContext.SaveChanges();

如何在.NET Core 8中自定义标识用户模型

在.Net 8 Visual Studio 2022中启用本机AOT发布时发布失败

除非首先访问使用的终结点,否则本地API上的终结点不起作用

Excel将';@';添加到具有范围的公式中

有没有更好的方法来使用LINQ获取整行的计算组

自定义ConsoleForMatter中的DI/Http上下文