Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create javascript POST request to server with Headers and Data

I use JS automation framework for testing iOS application. In the middle of a test I need to create POST request to server to some money to user and then verify that changes are reflected in UI.

Request looks like: wwww.testserver.com/userAddMoney?user_id=1&amount=999

but to authorize on server I need to pass special parameters to Header of request:

Headers: X-Testing-Auth-Secret: kI7wGju76kjhJHGklk76

Thanks in advance!

like image 706
z3us Avatar asked Nov 21 '12 08:11

z3us


People also ask

How do I make a POST request in JavaScript?

To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest() and then use the open() and send() methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event.

Can JavaScript get POST data?

POST data is data that is handled server side. So there is no way you can read a post data using JavaScript. Although the conclusion is correct (you can't get that data from javascript) the reasoning is wrong. The client (the browser) is the one that sends the POST data to the server in the first place.

What XMLHttpRequest method must be used to send a POST request to the server?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.

Which request will be used to send data to a server to create?

The PUT Method PUT is used to send data to a server to create/update a resource. The difference between POST and PUT is that PUT requests are idempotent.


1 Answers

So basically you want to set the header of a POST request. You can do it only if its an ajax request (You can't set headers for a normal html form submission request). Here is a way to set headers for an ajax request:

var request = new XMLHttpRequest();
request.onreadystatechange= function () {
    if (request.readyState==4) {
        //handle response
    }
}
request.open("POST", "url", true);
request.setRequestHeader("header", "blah blah");
request.setRequestHeader("Accept","text/plain");
request.send("post data");
like image 82
devsathish Avatar answered Oct 07 '22 15:10

devsathish