在React JS Axios Post Request

时间:2019-05-16 13:19:55

标签: reactjs cors asp.net-web-api2 axios

在React JS Axios Web Api发布请求中将对象作为参数传递时,我遇到了问题。我的Web方法被调用,但是参数以JSON格式的字符串传递,这引发异常。

我尝试在Axios中使用JSON.stringify()传递参数,并将其作为JSON格式的字符串传递。因此,我在传递参数时获取对象null异常。没有它不会调用服务方法,并且会引发错误

无法加载资源:服务器的状态为400(错误请求)[http://192.168.X.XXX/GHFService/api/Test/GetProduct] 从源“ http://192.168.X.XXX/GHFService/api/Test/GetProduct”开始对“ http://localhost:3001”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。 [http://localhost:3001/#/]

代码段如下:

来自React项目:

var objDummy = {
      Id: "1",
      Name: "Tomato"
    }

 AxiosApi.post(`Test/GetProduct`, JSON.stringify(objDummy))
      .then(res => {
        this.setState({ product : res.data });    

        console.log(res.data);  
      })

      .catch(error => {
        console.log(error);
      });
  }

从Web Api:

    [HttpPost]
    [ActionName("GetProduct")]
    public IHttpActionResult GetProduct([FromBody]JObject objDummy)
    {           
       int ID = objDummy["Id"].ToObject<int>();

        return Ok(products);
    }

有什么方法可以解析JSON格式的字符串。即

{{
 "{\"Id\":\"1\",\"Name\":\"Tomato\"}": ""
}} 

我要进入

{
  "Id": "1",
  "Name": "Tomato"
} 

从ARC(Advanced Rest Client)传递时得到的,并且工作正常,没有任何异常。

OR

有什么方法可以直接从React Axios传递对象,如下所示? 。因为当我尝试从应用程序为下面给出的服务方法使用相同方法时,参数将作为null传递。

public class Dummy
{
    public int Id { get; set; }
    public string Name { get; set; }
}

   [HttpPost]
    [ActionName("GetProduct")]
    public IHttpActionResult GetProduct(Dummy objDummy)
    {           
       int ID = objDummy.Id ;

        return Ok(products);
    }

0 个答案:

没有答案