You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript调用OData API时请求体自动添加双引号问题

问题原因与解决方案

原因分析

你遇到的双引号问题,本质是JSON序列化的规范要求:当TypeScript使用axios、fetch等工具发送请求时,如果请求头指定Content-Type: application/json,工具会自动把字符串类型的请求体用JSON.stringify()序列化,而JSON格式中字符串必须用双引号包裹。但Postman里你应该是选择了Text/Plain Text格式发送纯文本,所以不会添加双引号,这就是两者的差异。

举个典型的错误示例:

import axios from 'axios';

const odataQuery = "$filter=Id eq 1&$select=Name";
// 指定application/json后,axios会自动序列化字符串,导致请求体带双引号
axios.post('/api/odata/entity', odataQuery, {
  headers: { 'Content-Type': 'application/json' }
});

解决方法

1. 发送纯文本格式请求体(推荐)

修改请求头为Content-Type: text/plain,让请求工具直接发送原始字符串,不做JSON序列化:

import axios from 'axios';

const odataQuery = "$filter=Id eq 1&$select=Name";
axios.post('/api/odata/entity', odataQuery, {
  headers: { 'Content-Type': 'text/plain' }
});

如果用原生fetch API:

const odataQuery = "$filter=Id eq 1&$select=Name";
fetch('/api/odata/entity', {
  method: 'POST',
  body: odataQuery,
  headers: { 'Content-Type': 'text/plain' }
});

2. 后端配合接收JSON对象中的查询字符串(可选)

如果后端必须接收JSON格式,可以把查询字符串放在对象属性中,后端读取该属性值:

// TypeScript代码
const requestBody = { odataQuery: "$filter=Id eq 1&$select=Name" };
axios.post('/api/odata/entity', requestBody);

后端Asp.Net Core对应接收模型:

public class ODataQueryRequest
{
    public string OdataQuery { get; set; }
}

// 在接口中接收并处理
[HttpPost]
public IActionResult Post([FromBody] ODataQueryRequest request)
{
    var query = request.OdataQuery;
    // 后续OData处理逻辑
}

关键注意事项

  • 确认后端API已经适配了从请求体接收OData查询的逻辑(既然Postman能成功,这点应该没问题)。
  • 避免对纯字符串请求体做JSON序列化,这是双引号产生的核心原因。

内容的提问来源于stack exchange,提问作者Marwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:20:35