cryophoenix
cryophoenix

Reputation: 171

How can I change header properties in jQuery?

Basically, I have some jQuery that is attempting to post some JSON data to a server. This is the header that Firefox shows when I send it. However, if I use the "Edit and resend" feature of Firefox, I can force it to send properly. How can I change my code to force the headers I want? I have enabled cors on the server, done everything that is necessary to make it work if only the header were correct.

Here is my code followed by the headers:

$.ajax({

        url: "http://localhost:8080/users/login",
        method: 'POST',
        cors: true,
        data: dat,
        headers: {
            "Accept": 'application/json'
        },
        dataType: "application/json",
        success: function (response) {
            alert('YAY');
        },
        failure: function (response) {
            alert('Error', 'Invalid Credentials');
        }
    });

Fails (sent by code)

Accept:text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8  
Accept-Encoding: gzip, deflate  
Accept-Language: en-US,en;q=0.5  
Connection: keep-alive  
Content-Length:31  
Content-Type: application/x-www-form-urlencoded  
Host: localhost:8080  
Upgrade-Insecure-Requests:1  
User-Agent:Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/59.0

Works (manual edit in FireFox to the headers)

Accept: application/json
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 41
Content-Type: application/json
Host: localhost:8080
Pragma: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0

Upvotes: 1

Views: 224

Answers (1)

Barmar
Barmar

Reputation: 780879

dataType: is not supposed to be a MIME type, it's one of the small list of types that jQuery knows how to decode. If you use dataType: "json" it will send Accept: application/json, as well as automatically call JSON.parse() on the response.

To specify the format of the data you're sending, use the contentType: option, which does take a MIME type.

$.ajax({
    url: "http://localhost:8080/users/login",
    method: 'POST',
    cors: true,
    data: dat,
    dataType: "json",
    contentType: "application/json",
    success: function (response) {
        alert('YAY');
    },
    failure: function (response) {
        alert('Error', 'Invalid Credentials');
    }
});

Upvotes: 1

Related Questions