【问题标题】:Why when I send a post method with ajax, the data parameter is null?为什么我用ajax发送post方法时,data参数为null?
【发布时间】:2021-06-30 23:27:33
【问题描述】:

当我发布到我的 api 休息服务器时,数据发送为 null,如图所示 Post request

并且在数据库中,值被保存为 null data base

这是来自 axios 请求的代码

const fileUploadHandler = () => {

        const config = {
            headers: {
                'content-type': 'text/json'
              }
          }
        axios.post("https://localhost:44387/api/Diagrama?nombre=ejemplo", {imageBase64}, config)
        .then(res => {
            console.log(res);
        })
        .catch(error => {
            console.log(error);
        }); 
    }

这是asp.net中控制器的代码

[HttpPost()]
    public String Post( [FromUri]string nombre, [FromBody]  string plano)
    {
        tbl_Diagrama diagrama = new tbl_Diagrama(nombre, plano);
        Console.WriteLine(plano);
        
        bdAplicacionServidor.diagramas.InsertOnSubmit(diagrama);
        bdAplicacionServidor.SubmitChanges();
        return plano;
    }

【问题讨论】:

  • 首先,那个时候变量imageBase64里面是什么?在您尝试使用它的 fileUploadHandler 的上下文中,它看起来确实是未定义的。

标签: reactjs ajax asp.net-web-api axios


【解决方案1】:

原因是您正在寻找 URL 中的参数。但是你没有 Url/Uri 输入。但是,您确实传递了一个查询参数。区别如下:

这是您的完整网址:

https://localhost:44387/api/Diagrama?nombre=ejempl

这是你的 URI:

https://localhost:44387/api/Diagrama

?之后是你的查询参数:

?nombre=ejemplo

所以您的代码正在查看 https://localhost:44387/api/Diagrama 并试图找到您未在 Uri/Route 中指定的 nombre。相反,您需要告诉您的代码从查询参数中获取它,如下所示:

[HttpPost]
public String Post([FromQuery] string nombre, [FromBody]  string plano)

如果您确实想从 Route/Uri 中获取它,那么它将如下:

[HttpPost("{nombre}")]
public String Post([FromRoute] string nombre, [FromBody]  string plano)

请求将如下所示:

https://localhost:44387/api/Diagrama/ejempl

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    相关资源
    最近更新 更多