Wednesday, February 22, 2017

How to send Cookie in Request header

I did one file upload with Form data by using fetch. I tried to send Cookie and content type as multipart/form-data. But its not taking these two attributes in header. Finally I solved it through ajax as well as fetch.

1. If you want to send cookie you must add credentials like below.

fetch('/users', {
  credentials: 'same-origin'
})

Suppose if its a cross origin request, credentials should be like below.

fetch('https://xxxxxxxx.com:4321/users', {
  credentials: 'include'
})

and Finally you dont want to add content type as multipart/form-data. Your request will add this automatically.

2. Suppose if you are using ajax request,  your code should be like below.

$.ajax({
       url : 'xxxxxxxxxxxxxxxxxxxxx',
       type : 'POST',
       data : formData,     // form data appended values
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType -  It will set multipart by request automatically
       success : function(data) {
           console.log(data);
           alert(data);
       }
});


Check Internet explorer and open Network tab (F12) request header. Now all the header attributes were added perfectly.

Chrome may not show cookies in network tab, check Application tab, there cookies will be stored.


1 comment: