首页 > 解决方案 > JSON.stringify() 返回 null

问题描述

为什么会typeof(JSON.stringify(outputdata))在调试控制台中返回一个字符串,而我在后端(.NET 5)中收到 null?

后端部分:

[HttpPost]
        [Route("createpost")]
        public async Task<IActionResult> CreatePost([FromBody] Article article)
        {
            Console.WriteLine("CONTENT: " + article.Content);
    
            return Json(article);
        }

outputData是我的 JSON

Article.cs 模型:

public class Article
{
    public string Content { get; set; }
}

以下代码是我的 POST 请求:

fetch('/createpost', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      Content : JSON.stringify(this.outputData)
    })
  });

Content : JSON.stringify(` ${this.outputData} `)返回未定义

标签: javascript.net

解决方案


它已经被第一个字符串化JSON.stringify,第二个将字符串化的 json 视为字符串。

尝试:

fetch('/createpost', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      Content : this.outputData
    })
  });

推荐阅读