JQuery POST request in TypeScript

I am trying to talk to the API using TypeScript and jQuery (from a specific type).

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); 

Running a query and looking at what Fiddler captures is rather strange.

Fiddler jQuery request

The HTTP verb is invalid and the headers are not included in the Access-Control-Request headers as a standard header.

JQuery 3.2.0 and the most recent index.d.ts of definitely typed .

I can create an HTTP request in Fiddler:

Fiddler Request

The query I'm trying to create is:

Fiddler Output

Update

I tried manipulating dataType to get around pre-flight checks :

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

Update 2

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

+8
jquery typescript
source share
1 answer

This is just normal CORS doing its job. Make sure you serve the html site containing your script from the same URL where your API is located. eg:.

your html / script should be located under

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

then an ajax call

http: // localhost: 1234 / api / Controller

there should not be any problems, since the script issuing the request comes from the same URL / port, and there is no need to check.

Thus, you should get around the need for a preliminary browser check, which determines whether the request is submitted in accordance with CORS.

Alternatively, include CORS in your API , but make sure that you do not open the API to call from any possible (web) client there to prevent misuse.

Another possible way to get more control over your URLs might be to switch to full IIS even on your DEV machine, but there may be other / better ways to achieve this (I don't go so deep into .NET Core ATM hosting, to provide a better sample, but others may)

+5
source share

All Articles