2

I need to call a webapi POST method using javascript.

The method accepts a model. I am able to invoke this method correctly from POSTMAN and also see the entries in the database.

    // POST api/values
            [HttpPost]
            public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
            {
                try
                {
                    Debug.WriteLine("In post method");
                    var connstr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
                    Debug.WriteLine("initializing dbconnection");
                    var db = new RamDbDataContext(connstr);
                    Debug.WriteLine("mapping entity");
                    var inspectionPhoto = new DBLinq.InspectionPhoto
                    {
                        InspectionId = iPhoto.InspectionId,
                        InsertEmployee = iPhoto.Employee,
                        UpdateEmployee = iPhoto.Employee,
                        Photo = iPhoto.Data,
                        InspectionCategoryId = 8,
                        UpdateDate = DateTime.UtcNow,
                        InsertDate = DateTime.UtcNow
                    };
                    Debug.WriteLine("inserting entity");
                    db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
                    db.SubmitChanges();
                    Debug.WriteLine("done inserting entity");
                    int id = inspectionPhoto.Id;
                    return Ok(id);
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return Ok(-1);
                }    
            }

When I try to call this method from javascript, it doesn't reach the endpoint. I have played around with CORS settings but that hasn't helped much.

Here is my javascript code to invoke this method.

     <script>
            function callwebapi()
            {
                jsonIn = document.getElementById("mytext").value;
                console.log('++As you are+++');
                console.log(jsonIn);
                console.log('++As you are+++');
                const uri = 'https://localhost:44304/api/values';
                fetch(uri, {
                    method: 'POST',
                    cache: 'no-cache',
                    credentials: 'same-origin',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        'User-Agent': 'PostmanRuntime/7.28.4'
                    },
                    body: jsonIn
                })
                    .then(result => console.log(result.status))
                    .then(response => response.json())
                    .then(response => console.log('Success: ', response))
                    .catch(error => console.error('Failure: ', error));
            }
    
        </script>
        <textarea id="mytext">
            {"Id": -1,   "InspectionId": 95,   "CategoryId": 9,   "Employee": "Roger Moore",   "Data": null}        
        </textarea>
        <button onclick="callwebapi();">Click this and send your data!</button>

The error I get in the chrome browser console is

TypeError: Failed to fetch at callwebapi (About:89:13) at HTMLButtonElement.onclick (About:110:37)

I created an ASP .NET Web Application and started with web forms project. The client code was created on the About.cshtml page.

I need to eventually merge this code into an existing application. How do I go about fixing this error and making a successful call?

Edit: Postman call request. This is how I am making the call from Postman.

Postman call headers

Postman Call Image

abhi
  • 3,082
  • 6
  • 47
  • 73
  • Can you show how did you use a Postman to get a result pls? – Serge Jan 13 '22 at 10:05
  • There isn't enough information here to answer accurately but it looks like it [might be this](https://stackoverflow.com/a/10892392/542251). Note: different ports count as cross origin – Liam Jan 13 '22 at 16:46
  • @Liam The cors issue had reared its head in one of the iterations of this code. It has now vanished and this is the present issue. – abhi Jan 13 '22 at 17:19

1 Answers1

0

I had to make changes to the client-side code and the server-side code to make this work.

Changes to client-side code

  function takepicture() {
            var context = canvas.getContext('2d');
            if (width && height) {
                canvas.width = width;
                canvas.height = height;
                context.drawImage(video, 0, 0, width, height);

                
                var data = canvas.toDataURL('image/png');
                
                photo.setAttribute('src', data);
                console.log(data);
                console.log('+++++++++++++++++++JUST NOT DATA++++++++++++++');
                var dataPart = data.split(',')[1];
                console.log('+++++++++++++++++++JUST DATA++++++++++++++');
                console.log(dataPart);
                console.log('+++++++++++++++++++JUST DATA++++++++++++++');
                class nemo {
                    constructor(Id, InspectionId, CategoryId, Employee, Data) {
                        this.Id = -1;
                        this.InspectionId = 95;
                        this.CategoryId = 8;
                        this.Employee = 'Scanner01';
                        this.Data = dataPart;
                    }
                }
                const instanceofnemo = new nemo();
                callwebapi(instanceofnemo);
            } else {
                clearphoto();
            }
        }

        function callwebapi(someclass)
        {
            console.log(JSON.stringify(someclass));
            const uri = 'https://localhost:44304/api/values';
            fetch(uri, {
                method: 'POST',
                mode:'no-cors',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(someclass)
            })
                .then(response => response.json())
                .catch(error => console.error('Some Failure Occurred.', error));
        }

Changes to server-side code:

[System.Web.Http.HttpPost]
        public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
        {
            try
            {
                Debug.WriteLine("In post method");
                var connstr = ConfigurationManager.ConnectionStrings["RAMSESTest_2021_11_02ConnectionString"].ConnectionString;
                Debug.WriteLine("initializing dbconnection");
                var db = new RamDbDataContext(connstr);
                Debug.WriteLine("mapping entity");
                var inspectionPhoto = new DBLinq.InspectionPhoto
                {
                    InspectionId = iPhoto.InspectionId,
                    InsertEmployee = iPhoto.Employee,
                    UpdateEmployee = iPhoto.Employee,
                    Photo = iPhoto.Data,
                    InspectionCategoryId = iPhoto.CategoryId,
                    UpdateDate = DateTime.UtcNow,
                    InsertDate = DateTime.UtcNow
                };
                Debug.WriteLine("inserting entity");
                db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
                db.SubmitChanges();
                Debug.WriteLine("done inserting entity");
                int id = inspectionPhoto.Id;

                HttpResponseMessage responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                responseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
                responseMessage.Content =new StringContent(id.ToString(), Encoding.UTF8, "application/json");
                return ResponseMessage(responseMessage);
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return Ok(-1);
            }    
        }

//WebApiConfig.cs

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
abhi
  • 3,082
  • 6
  • 47
  • 73