Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery POST request in TypeScript

I'm trying to talk with an API using TypeScript and JQuery (from Definitely Typed).

let ajaxsettings: JQueryAjaxSettings = {
    url: this.url,
    contentType: "application/json",
    type: "POST",
    data: JSON.stringify(this.apiRequest),
    processData: false,
    success: ( data, textStatus, jQxhr ) => {
        console.log("Response:" + JSON.stringify(data));
    },
    error: ( jqXhr, textStatus, errorThrown ) => {
        console.log("Error Response; " + JSON.stringify(jqXhr));
    },
    headers: {
        "X-UserName": "blahblah",
        "X-Password": "blahblah"
    },
    beforeSend: (request) => {
        request.setRequestHeader("X-APIKey", "blahblahblah");
    }
};
$.ajax(ajaxsettings);

Making the request and looking at what Fiddler captures is rather odd.

Fiddler JQuery request

Wrong HTTP verb, and headers are included in Access-Control-Request-Headers not as a standard header.

JQuery 3.2.0, and the latest index.d.ts from Definitely Typed.

I could create a HTTP request in Fiddler:

Fiddler request

The request I'm trying to create:

Fiddler output

Update

I've tried juggling the dataType to get around preflight checks:

contentType : "text/plain",
method: "POST",
type: "post",
dataType: "json",

Update 2

The API is hosted within IIS Express from Visual Studio 2017 (using .NET Core), and the website is hosted using lite-server. This code works fine, when taking out the custom headers.

like image 905
wonea Avatar asked Apr 11 '17 09:04

wonea


1 Answers

This is just normal CORS doing its work. Make sure you are serving the html-site containing your script from the same URL/Port where your API is located. e.g.:

your Html/Script should be located under

http://localhost:1234/web/index.html

then an AJAX-call to

http://localhost:1234/api/Controller

should be no problem, as the script issuing the request originates from the same URL/Port and there is no need to do a check.

This way, you should circumvent the need for a pre-flight check of the browser which determines if the request is granted access according to CORS.

Alternatively, enable CORS in your API, but make sure you don´t expose the API to be callable from every possible (Web-)client out there, to prevent misuse.

Another possible route to gain more control over your URL´s might be to switch to full IIS even on your DEV-machine, but there might be other/better ways to achieve this (am myself not so deep into hosting .NET Core ATM to provide a better sample, but others might)

like image 117
earloc Avatar answered Sep 28 '22 06:09

earloc