XMLHttpRequest Post Method - Headers are stopping function - ruby-on-rails

I'm trying to send an XMLHttpRequest object to my Rails server but the headers are causing my function to stop. Here are my observations:
When I comment out the 3 lines of code that set the headers, then xhr.readyState will eventually equal 4 (alert boxes within the anonymous function fire off).
If any one of the 3 header lines are uncommented, then the xhr object never changes state (none of the alert boxes ever fire off).
function saveUserProfile(){
var user_email = $('#userEmail_box').val();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200)
{
alert("Yes: " + xhr.readyState);
}
alert("No: " + xhr.readyState);
}
var method = 'POST';
var params = 'userEmail=user_email';
var url = 'http://localhost:3000/xhr_requests.json';
var async = true;
//Need to send proper header information with POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.open(method, url, async);
xhr.send(params);
}
My three questions are:
What do I need to change in the code above in order to send data through the POST method?
I'm under the impression that the POST method requires some headers to be sent but am not clear about which ones though "xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');" seems to be one that is often mentioned in references. Can somebody help me understand a) why headers need to be sent and b) which ones need to be sent?
I'm using a rails server and am developing locally. Ultimately, this code will be executed on the client side of a mobile device which will go to a hosted rails server for passing and receiving data. Are there limitations with using the POST method with a rails server? Keep in mind that I plan to use JSON when sending information to the client from the server.
Thanks!
UPDATE: The headers should come AFTER the opening the xhr request but BEFORE sending it:
xhr.open(method, url, async);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.send(params);
Hope this post saves somebody else 4 hours.

Does your web page with the JavaScript code also live on localhost:3000? If not, this is considered a cross-domain request, and your server will need to return special headers. So you have two options:
1) Host the web page on the same domain as the server, which will make this a same-domain request.
2) Have your server return the appropriate CORS headers. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Related

Rails request.headers data not updating without refresh

When I hit site for first time, then results of request.headers[HTTP_ACCEPT] is "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
but between internal links requests it shows text/html, application/xhtml+xml
until I hard refresh the page.
Is it due to turbolinks or any other issue?
It's a turbolinks issue. By default, the turbolinks' XMLHttpRequest, only send the headers "text/html, application/xhtml+xml", but you can send the "image/webp" header by capturing the request-start event like this:
document.addEventListener("turbolinks:request-start", function(event) {
var xhr = event.data.xhr
xhr.setRequestHeader("Accept", "image/webp")
})
The question is how to know from javascript whether or not the browser accepts webp images to send the "image/webp" header to the server.
You can use the Modernize library or a custom function that guess if webp is available when trying to decode a small webp image like described here: https://developers.google.com/speed/webp/faq. However, these solutions add a certain overhead that precludes the benefit of the fastest load time of webp images.
Maybe, the most efficient solution is to create a boolean cookie in the server side to store whether or not webp images are accepted. The cookie is stored with the first browser GET call to the server. In subsequent turbolinks calls you can check this cookie in your javascript code:
document.addEventListener("turbolinks:request-start", function(event) {
browserAcceptsWebp = document.cookie.includes('webp_available=true');
if (browserAcceptsWebp) {
var xhr = event.data.xhr;
xhr.setRequestHeader("Accept", "image/webp");
}
});

502 Bad Gateway on POST/PUT Web API Calls from ASP.NET Core MVC

I'm getting strange errors in ASP.NET Core when calling Web API that I have created for the application. GET requests go through fine and return all of the data that they should, but my POST/PUT commands all return a 502, specifically from the MVC application. I can call the API's from Postman and get a proper response and the object is created in the database.
502 - Web server received an invalid response while acting as a
gateway or proxy server. There is a problem with the page you are
looking for, and it cannot be displayed. When the Web server (while
acting as a gateway or proxy) contacted the upstream content server,
it received an invalid response from the content server.
I am impersonating an Integrated Windows Login with the following code for all web requests to the API:
async Task Action()
{
response = await _service.CreateIncident(model);
}
await WindowsIdentity.RunImpersonated(identity.AccessToken, Action);
CreateIncident(model):
using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
{
var newIncident = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var response = await client.PostAsync(hostUri, newIncident);
return response;
}
There is also one GET Request that I make through Ajax to get an incremented ID to display to the user before they create their new Incident that returns a 502 Bad Gateway as well. Is this an IIS Setting that is incorrect?
If you use WindowsIdentity.RunImpersonated and an asynchronous function, it will not work. You must be synchronous when doing non-GET requests. I have updated my GitHub issue, I'm hoping to get this bug addressed. If you are a future visitor to this topic, you can see where this ended up here.
I think it also depends on the size of the data. Smaller packages work, larger ones don't.

receiving post variables from an external source in zendframework 2

i am working on a zendframework 2 project and want to receive post variables from an external source.
the source where the values will come from is a payment site (i.e world pay and paypal). i.e the return values of a payment confirming that payment has been made.
on the external site, i simply gave the URL of the web page that i want the information to be returned to:
http://example-site.com/payments/payment-made
then in action function on the controller page i did the following;
public function paymentMadeAction()
{
$contents = file_get_contents('php://input'); // read request contents
$data = explode('&', $contents);
if ($contents)
{
foreach($data as &$entry) {
$entry = explode('=', $entry);
$entry[1] = urldecode($entry[1]);
}
unset($entry);
}
print_r($data);
}
nothing happens though. i mean, i tested it but the values are not being received. when i went to the external source to check if my site received the information it confirmed that the information had been successfully sent
is there a special procedure that needs to be followed when receiving information from an external source in zend framework 2
would really appreciate any guidance or advise.
update:
below is a sample of the post variable that should be returned to the site; its a simply http object
POST /fail?installation=XXXXXX&msgType=authResult HTTP/1.0
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Host: www.worldpay.com
Content-Length: 973
User-Agent: WJHRO/1.0 (worldPay Java HTTP Request Object)
region=new+format+region&authAmountString=%26%23163%3B10.00&_SP.charEnc=UTF8&desc=&tel=&address1=new+format+address1)
you are doing it in the absolute WRONG way, the correct way to get post(or query or route ) variables in ZF2 action :
$this->params()->fromPost();
or
$this->request->getPost()->toArray();

$httpProvider interceptor how to read all headers

I have an interceptor using $httpProvider as follwos (taken from Angular doc)
$httpProvider.interceptors.push(function ($q) {
return {
'response': function (response) {
// look for the antiforgerytoken and update dataService with the same.
return response || $q.when(response);
}
};
});
using the debugger I see that this method is called on each response and when I look at the 'response' object pased I see only one header, namely the Accept-Header as shown below
When I look at the response packet in the chrome I see many more headers
My question is why am I not able to see all the headers in the response?
Specifically I want to read the cookie for AntiforgeryToken and store it, how can I do that?
I believe the cookie AntiforgeryToken is a HttpOnly cookie and cannot be accessed from javascript. Can you check
See some details here http://blog.codinghorror.com/protecting-your-cookies-httponly/
Such cookies are mean for server exclusively.

POST request and Node.js without Nerve

Is there any way to accept POST type requests without using Nerve lib in Node.js?
By default the http.Server class of Node.js accepts any http method.
You can get the method using request.method (api link).
Example:
var sys = require('sys'),
http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(request.method);
response.end();
}).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
This will create a simple http server on the port 8000 that will echo the method used in the request.
If you want to get a POST you should just check the request.method for the string "POST".
Update regarding response.end:
Since version 0.1.90, the function to close the response is response.end instead of response.close. Besides the name change, end can also send data and close the response after this data is sent unlike close. (api example)

Resources