1

I am confused why my c# WebAPI call is failing to fetch from JavaScript and is always just returning an empty string.

Here is my method in my C# API controller

    [AllowAnonymous]
    [Route("GetApiExample")]
    [HttpPost]
    public IHttpActionResult GetApiExample()
    {
        return Ok(new { success = true });
    }

Here is my javascript

fetch('https://localhost:44363/api/Example/GetApiExample', {
  method: 'POST',
  mode: 'no-cors',
})
  .then((response) => response.text())
  .then((json) => console.log(json));

I'm assuming it must be something on the c# side or the fact is needs no-cors on it.

Anyone have any ideas?

** UPDATE **

I have updated to the answer as below but this still brings back an empty string

enter image description here

user3284707
  • 3,033
  • 3
  • 35
  • 69

3 Answers3

0

It's supposed to be an object to serialize in parameter, not a string. Also you have 3 'c' letters for 'succcess' in your code.

 public IHttpActionResult GetApiExample()
 {    
     return Ok(new { success = true });
 }

UPDATE:

mode: 'no-cors'

This doesn't exactly allow cors requests from browser. Browser will always deny http requests to other domainnames, unless CORS is enabled that target domain. 'no-cors' just disables options to check the cross domain. If you're using different port numbers between two projects, you have to enable Access-Control-Allow-Origin header on your api project by enabling CORS.

Noldor
  • 1,122
  • 9
  • 22
  • Thank you for your response, I have updated the code, but this is still bringing back an empty string – user3284707 Jun 28 '20 at 09:15
  • @user3284707 did you check your browser console and network section and make sure the response is present and you're not having any HTTP errors?? – Noldor Jun 28 '20 at 09:25
  • Hi, yeah i've checked and it has a status 200 – user3284707 Jun 28 '20 at 09:26
  • 1
    @user3284707 You should also change response.text() to response.json() according to here : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – Noldor Jun 28 '20 at 09:28
  • I had this originally but it comes up with a parsing error which is why I put it to text to see what the response was. "Uncaught (in promise) SyntaxError: Unexpected end of input" – user3284707 Jun 28 '20 at 09:29
  • @user3284707 the error might be because you didn't have quotes for json field name in the first version.. also, is your page address in the same domain with this url, main page port number is same with fetch URL ?? – Noldor Jun 28 '20 at 09:33
  • I've updated the response to JSON as you described, but the address is not in the same domain, I am testing accessing my WebApi from a static website hosted using npm start, this is why I added the mode: 'no-cors' onto the fetch request as it complained about this before I did this. – user3284707 Jun 28 '20 at 09:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216817/discussion-between-noldor-and-user3284707). – Noldor Jun 28 '20 at 09:45
0

You can use ajax for post request like this.

$.ajax({
    type: 'POST',
    url: 'url',
    crossDomain: true,
    data: '{}',
    dataType: 'json',
    success: function(data, textStatus, jqXHR) {
        var value = data;
    },
    error: function (data, textStatus, errorThrown) {
        //Handle error
    }
});
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • Thank you, I had already tried this, in the end it was CORS not being setup properly on the serverside, i've added the solution as an answer – user3284707 Jun 28 '20 at 10:12
0

The answer in the end was that CORS was not properly enabled on the server side

https://stackoverflow.com/a/54800308/3284707

I needed to add the following to my WebApiConfig

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Complete code is this...

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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


        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);
    }
}

Then my javascript remove the mode: no-cors

fetch('https://localhost:44363/api/Example/GetApiExample', {
  method: 'POST',
})
  .then((response) => response.json())
  .then((json) => console.log(json));
user3284707
  • 3,033
  • 3
  • 35
  • 69