Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery set header in post request

Tags:

jquery

I need to simulate this curl command

curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"username":"pippo","password":"secret123"}' http://url.org/api/login

via jquery, I made in this way

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8",
        "Content-Type": "application/json; charset=utf-8"
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

I still have has content-type text/html. Is it right?

like image 632
Mattia Lipreri Avatar asked Mar 22 '23 22:03

Mattia Lipreri


1 Answers

Try beforeSend in your jQuery AJAX call:

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      beforeSend: function(xhr){
                xhr.setRequestHeader("Content-Type","application/json");
                xhr.setRequestHeader("Accept","application/json");
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});
like image 179
electroid Avatar answered Apr 08 '23 05:04

electroid