How come I'm facing difficulties when trying to send a post request to my WebApi using AngularJS's POST method?

I've uploaded "mytest.html" to the IIS server, and this project consists of WebApi and AngularJS. However, I am unable to make a correct request to my WebApi. I'm not sure why?

【HTML Code Snippets】

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    </head>

    <body>
       <div ng-app="A" ng-controller="Test">
           <form method='post' name='myForm'>
               <table width="100%">
                  <tr>
                      <td>Name:</td>
                      <td><input type='text' ng-model='user.name' name='myname' required/>
                               <span style='color:red' ng-show='myForm.myname.$dirty && myForm.myname.$invalid'>Name cannot be empty!</span>
                      </td>
                 </tr>

                  <tr>
                      <td>Gender:</td>
                      <td>
                        <div ng-repeat='s in sexs'>
                        <input type='radio' ng-model='user.sex' name='mysex' value='{{s}}'>
                        {{s}}
                        </div>
                      </td>
                 </tr>
                 <tr>
                       <td>Hobby:</td>
                       <td>
                       <select ng-model='user.love' name='selLove'>
                           <option ng-repeat='l in loves' value='{{l}}'>{{l}}</option>
                       </select>
                       <span style='color:red' ng-show='selChoice(myForm.selLove.$dirty);'>You cannot choose "Please choose"</span>
                        </td>
                 </tr>
             </table>
             <input type ='submit' value='Submit' ng-click='isDisable();'/>
           </form>
      </div>

    <script>

         var app = angular.module('A',[],function($httpProvider){

            $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
         });


         app.controller('Test',function($scope,$http){

           $scope.user = {};

           $scope.sexs = ['M','F'];
           $scope.loves = ['Please choose','Programming','Piano','Swimming'];

           $scope.user.sex = 'M';
           $scope.user.love = 'Please choose';

           $scope.selChoice= function(isDirty){
                var isFalse = (myForm.selLove.value == 'Please choose' && isDirty);
                $scope.myForm.selLove.$invalid = isFalse;
                $scope.myForm.$invalid |= isFalse;
                return isFalse;
           };

           $scope.isDisable = function(){

                $scope.selChoice(true);

                var requestData = $.param($scope.user);
                alert(requestData);

                if($scope.myForm.$invalid){
                    alert('Invalid form');
                }
                else{
                    $http({
                        method:'POST',
                        data: requestData,
                        url:'http://localhost:60031/api',
                        success: function (data){
                            alert(JSON.stringify(data));
                        }
                    });
                }
           };
         });
    </script>

      </body>
    </html>

【WebApi Code Snippets】

 namespace AngularJSDemo.Controllers
    {
        using Models;
        using System.Web.Http;

        public class DefaultController : ApiController
        {
            [HttpPost]
            public Person GetPerson([FromBody] Person p)
            {
                return p;
            }
        }
    }

【Model Code Snippets】

 namespace AngularJSDemo.Models
    {
        public class Person
        {
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Love { get; set; }
        }
    }

【Register Code Snippets】

namespace AngularJSDemo
{
    using Newtonsoft.Json.Serialization;
    using System.Net.Http.Formatting;
    using System.Web.Http;

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();

            var jsonFormatInstance = new JsonMediaTypeFormatter();
            jsonFormatInstance.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Add(jsonFormatInstance);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional, controller="Default" }
            );

        }
    }
}

The error displayed in the console of my Google Chrome is:

angular.js:10695 POST http://localhost:60031/api 415 (Unsupported Media Type)


I also attempted to use JSON format but without any success :(

$http({
                    method:'POST',
                    data: {p:$scope.user},
                    url:'http://localhost:60031/api/Default',
                    success: function (data){
                        alert(JSON.stringify(data));
                    }
                });

And the Content-Type set is as follows:

var app = angular.module('A',[],function($httpProvider){

                $httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
             });

Due to having different ports and domains, I also made these adjustments:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
        <add name="Access-Control-Request-Methods" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Answer №1

Oops, there seems to be an issue with the URL provided

The correct URL should look like this: http://localhost:60031/api/Default

$http({
                        method:'POST',
                        data: requestData,
                        url:'http://localhost:60031/api/Default',
                        success: function (data){
                            alert(JSON.stringify(data));
                        }
                    });

Furthermore, it is recommended to send the data as JSON instead of form-urlencoded

Answer №2

On the whole, my conclusion is:

1) It is essential to utilize the default settings and specify the headers as "application/json" in the following manner:

$http({
                    method:'POST',
                    data: $scope.user,
                    url:'http://localhost:60031/api/Default',
                    headers:{'Content-Type':'application/json'}
                }).success(function (data){
                        alert(JSON.stringify(data));
                    });

2) Additionally, we must enable "CORS" (Cross-Origin Resource Sharing) for our WebApi, this is the ultimate solution.

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

Protractor tests are successful when run locally, but encounter failures when executed on Travis-CI

I recently integrated end-to-end tests using Protractor into my AngularJS application. Testing them locally showed that they all pass, but upon committing to GitHub and Travis for CI, most of the tests fail. The failing tests seem to be those requiring na ...

Show a nested array retrieved from JSON in a React component

I need assistance in displaying data from my JSON file, particularly an innested array using map(). The field I want to display as a list is analyzedInstructions, which looks like this: How to prep (from p How to prep /p) Steps: Remove the cauliflower&a ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

Updating the status of the checkbox on a specific row using Typescript in AngularJS

My goal is to toggle the checkbox between checked and unchecked when clicking on any part of the row. Additionally, I want to change the color of the selected rows. Below is my current implementation: player.component.html: <!-- Displaying players in ...

Is it possible to analyze the performance of NodeJS applications using Visual Studio Code?

I have managed to establish a successful connection between the VS Code debugger and my remote NodeJS target through the Chrome protocol. I am aware that this protocol allows for profiling and performance measurements within the Chrome Dev Tools, but I am ...

Angular JS response has a property of `$resolved` with a value of false

I am in the process of setting up an Angular JS application that will interact with a Django REST API. My goal is to display an HTML list of classrooms. Here is the template I have created: <body> <div ng-app="schoolApp" ng-controller="sc ...

React Error: Unable to Call function this.state.Data.map

I'm encountering an issue with mapping objects in ReactJS. Even though I am able to fetch data, when I try to map it, I receive the following error: this.state.Data.map is not a function Here's the code snippet: import React, { Component } fro ...

Is it necessary to match GET and POST routes only if a static file does not match?

I am encountering an issue with my routes and static definitions in Express. Here is my route setup: app.get('/:a/:b/:c', routes.get); Along with this static definition: app.use('/test', express.static(__dirname + '/test')); ...

Steps to retrieve the value of a particular row in a table using vuejs

Can you help me retrieve the value of a specific row in a table using VueJS 2? Here is an image of my current table: I need assistance with obtaining and displaying the last value from a loop in the "SHOW QR Button" within my code snippet. The button shou ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Strategies for tracking distinct property values in Firestore

Is it possible to count the occurrences of unique values in Firestore? For instance, if there are 1000 documents with dates and only 50 different dates repeated, how can I get a list of each date along with its frequency? Context: These documents represe ...

Utilizing the Facebook Like Button with ASP.NET MVC in C#

I have recently developed a website showcasing various products, with the intention of displaying product details when users click on each item. I am looking to integrate the Facebook Like Button into these product pages. After consulting http://developer ...

Denied access to [Any Url] as it breaches the specified Content Security Policy directive and refused to connect

Struggling to retrieve data using the Login() method within a post request, but encountering an error when the URL is transferred to its destination. Error: Refused to connect to 'http://smartlearner.com/SmartLearner/UserAccount/[email prote ...

Ways to transfer PHP output information using AngularJS

Welcome to my HTML page where I have added ng-app="myApp" and ng-controller="DashCtrl" <form action="" ng-submit="dashForm(dashdata)" method="post"> <input type="hidden" name="uid" ng-model="dashdata.uid" value="<?php echo $row ...

The Input element's onChange event is not functioning as expected

I am experiencing some issues with my code. I am trying to dynamically change the background color based on user input, but I am struggling to make it work. It seems like a simple task, so I must be missing something. Below is my HTML markup and jQuery: ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...