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!
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");
Related
I am trying to call a Firebase Cloud function written in python from my website. The function works perfectly when I call it from command line using curl, however, when I try to do the same from JavaScript I am getting the following issue. Essentially the JSON params are not being received.
How I am calling in JavaScript
var xmlhttp = new XMLHttpRequest();
var theUrl = "https://us-central1-scan2checkout.cloudfunctions.net/registerUser";
xmlhttp.open("POST", theUrl,true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send('{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
console.log(xmlhttp.responseText);
}
}
Cloud Function
def registerUser(request):
print(request) # Printing '<Request 'http://us-central1-scan2checkout.cloudfunctions.net/' [OPTIONS]>'
print(request.json) # Printing 'NONE' :(
auth = request.json['auth'] # Issue is here
# ... SOME STUFF ...
return {...},201
How it works when I use command line
time curl -v -X POST -d '{"auth":"ac_Fn0GuKLhuh8yltMVlmFeBkQpdpaTrqug"}' -H "Content-type: application/json" https://us-central1-scan2checkout.cloudfunctions.net/registerUser
If you run this now you'll probably get something like "Authorization code expired" which is correct.
To handle this request, you will need to set the appropriate Access-Control-Allow-* headers in your Cloud Function to match the requests you want to accept. Please see an example of a CORS function written in Python.
You will notice that CORS consists of two requests: a preflight OPTIONS request, and a main request that follows it.
The preflight request contains the following headers:
Access-Control-Request-Method - indicates which method will be sent in the main request.
Access-Control-Request-Headers - indicates additional headers along with the origin of the main request.
Let me know if it helps.
I have an API that authenticates the request based on the header fields and then returns a HTML page.
The request to this API has to be made in a way, such that the domain will change from domain1.com to domain2.com (Just like clicking a hypertext).
I cannot use <a>Link</a> because I need to add header fields.
And ajax cannot be used because it does not change controls from domain1.com to domain2.com.
Something like this did not make sense at all...
$.ajax({
// Use ajax to authenticate
...
success : function(path){
// Load the path for domain change
location.assign(path);
// Even this request should have a header field
},
...
})
I need the functionalities of both(changing domains and header usage) in a single request - if possible or at the least with 2 requests.
Any ideas to do this?
In order to send HTTP request with credential in header, and "change domain" when it is successful, you can use JSON response with 302 code and Location -- just a convention, browser behaviour won't be triggered.
An example response:
HTTP response code: 200 OK
HTTP response body:
{
status: 302,
location: 'domain2.com/result'
}
The Ajax code would look like:
$.ajax({
// Use ajax to authenticate, with credential in HTTP header
...
success: function(result){
if (result.status === 302) {
window.location = result.location;
}
},
...
})
2 HTTP requests will be used. One for Ajax, and another for the redirection.
I am trying to make a POST request to the server (Which is a REST service)via javascript,and in my request i want to send a cookie.My below code is not working ,as I am not able to receive cookie at the server side.Below are my client side and server side code.
Client side :
var client = new XMLHttpRequest();
var request_data=JSON.stringify(data);
var endPoint="http://localhost:8080/pcap";
var cookie="session=abc";
client.open("POST", endPoint, false);//This Post will become put
client.setRequestHeader("Accept", "application/json");
client.setRequestHeader("Content-Type","application/json");
client.setRequestHeader("Set-Cookie","session=abc");
client.setRequestHeader("Cookie",cookie);
client.send(request_data);
Server Side:
public #ResponseBody ResponseEntity getPcap(HttpServletRequest request,#RequestBody PcapParameters pcap_params ){
Cookie cookies[]=request.getCookies();//Its coming as NULL
String cook=request.getHeader("Cookie");//Its coming as NULL
}
See the documentation:
Terminate these steps if header is a case-insensitive match for one of the following headers … Cookie
You cannot explicitly set a Cookie header using XHR.
It looks like you are making a cross origin request (you are using an absolute URI).
You can set withCredentials to include cookies.
True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.
Such:
client.withCredentials = true;
This will only work if http://localhost:8080 has set a cookie using one of the supported methods (such as in an HTTP Set-Cookie response header).
Failing that, you will have to encode the data you wanted to put in the cookie somewhere else.
This can also be done with the more modern fetch
fetch(url, {
method: 'POST',
credentials: 'include'
//other options
}).then(response => console.log("Response status: ", response.status));
var http = {};
http.request = (function () {
function send(jsonObject, url) {
var jsonString = JSON.stringify(jsonObject);
var req = new XMLHttpRequest();
req.open("POST", url);
req.setRequestHeader("Content-Type", "application/json");
req.send(jsonString);
}
return {
send: send
};
})();
I am trying to use this javascript function to send data. However it gives me an error:
"XMLHttpRequest cannot load url. Response for preflight is invalid (redirect)"
What am i doing wrong?
Since you are setting the content-type to be json, this is considered a preflighted request. What this means is that essentially two requests are being made: the first one asks the server permission to make a request, and the second one is the actual request. For such cases, you need to at least check for origin of the request on your server side:
header('Access-Control-Allow-Origin: your origin url')
You might also have to check the request method:
header('Access-Control-Allow-Methods: POST')
i load inicio.jade with ajax req
$.ajax(
{
url:'/inicio',
cache: false,
type: 'GET',
}).done(function(web)
{
$('#contenido_nav_principal').fadeOut(600,function()
{
$('#contenido_nav_principal').empty();
$('#contenido_nav_principal').html(web);
$('#navegacion').animate({height:'600px'},200);
$('#contenido_nav_principal').fadeIn(600);
});
});
from this address in the server
app.get('/inicio',routes.inicio.inicio);
the problem is that i can access to the page with http://www.mypage.com/inicio
how can i restrict the access only to ajax requests and redirect to 404 error page if is not an ajax request
With expressjs, you can respond only to xhr requests like this:
function handleOnlyXhr(req, res, next) {
if (!req.xhr) return next();
res.send({ "answer": "only is sent with xhr requests"});
}
(in your example, routes.inicio.inicio would use the pattern above by checking req.xhr)
You can detect whether it is an Ajax request at the server side by checking HTTP_X_REQUESTED_WITH header. The value of HTTP_X_REQUESTED_WITH header should be XmlHttpRequest if it is an Ajax request.
You could override the beforeSend event on the .ajax() call. Per the documentation you can add custom headers to the request. This post gives an example.
Then you can have your page check for the presence of that custom header.