How to send Ajax POST request on https - javascript

I'm trying to make an Ajax POST request, but I keep getting a 404 error "GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
Don't know if it is because the site has https?
This is the code I have used:
var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.test.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
response = JSON.parse(xhr.responseText);
console.log(reponse);
}
};
xhr.send(JSON.stringify(params));
Any suggestions on how to make it work?

What is happening is that your backend / API is set up to require authentication and if a request is received without authentication, it redirects to the login page. You can see this in your error response:
"GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
But the other problem is that you don't have a login page! So that explains the 404 Not Found response.
Either disable authentication on your API for testing, or include authentication / credentials in your Ajax request.

Related

Once I'm logged in how can I send an authenticated POST request?

One more question:
I built a simply script where I use XmlHttpRequest to login to a server like this:
var requestUrl = 'https://www.testsite.com/engine2/api/Login';
xmlhttp.open('POST', requestUrl, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.withCredentials = true;
xmlhttp.send("username=myusername&password=mypassword&grant_type=password");
}
I'm able to login and I receive a 200: true http status response. Now that I'm logged in I'd like to send the following POST request:
xmlhttp = new XMLHttpRequest();
var requestUrlCreate = 'https://www.testsite.com/engine2/api/channel/47377/post/publish';
xmlhttp.open('POST', requestUrlCreate, true);
xmlhttp.send(formData);
My problem is that this last request returns error 403 (Forbidden) as if it was not authenticated. I think I'm missing something basic (maybe should I store session credentials in a cookie?).
Could you please let me know? Thank you!

Cross-Origin Request Blocked: in javascript using XMLHttpRequest

I am trying to send a HTTP request in javascript using XMLHttpRequest and so I am using the following code in an HTML file. I have a server running which returns a dictionary of form {'test' : 'string'}.
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/test", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send();
xhr.onreadystatechange = processRequest;
console.log(xhr.status)
function processRequest(e)
{
if (xhr.readyState == 4)
{
alert(xhr.responseText);
}
}
</script>
However in spite of adding the header, I am getting a Cross-Origin Request Blocked: error in my console when I try to print xhr.status in the console it shows 0 as response.
I am using flask server which shows a bad message error on using HTTPS, so I am using an HTTP request.
You can not control CORS from front end. You have to put the CORS module to your back end server.
check the link flask cors.

XHR Post Response 200 but Failed to Execute Send

I am having an issue with a post to an Api.
The Api is using OAuth, I am generating all the valid information and posting it to the request_token url.
In Chrome Network tab I get a response 200 with the correct token in response,
but in the console I get an error and cannot get the response data.
NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://www.obsidianportal.com/oauth/request_token'.
If I set it to Async then it fails outright with a POST (cancelled)
xhr.open("POST", "https://www.obsidianportal.com/oauth/request_token", false);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//xhr.responseType = "text/html";
//xhr.responseType = "text";
xhr.addEventListener("error", function() { console.log(xhr, arguments); }, false);
xhr.send(postData);
PostData is the generated OAuth information which is only valid once, so it is hard to debug.
Any help on this issue would be great.

Using javascript to submit a post request to a server

I am working on a web crawler that can integrate with our partner portals and submit post requests to make bid changes.
The trouble is that the crawler runs in an environment which cannot execute jQuery, only native Javascript.
I have determined that the following AJAX code successfully sends the post request:
$.ajax({
type: "POST",
url: "http://acp.example.com/campaigns/122828",
data: "data-string"
});
Is there a way to translate the above statement into native javascript so that the crawler can execute it?
UPDATE
When executing hex494D49's native Javascript below, I am receiving a "NetworkError: 404 Not Found - http://acp.fyber.com/campaigns/122828" message.
However, when I execute the original AJAX code in firebug, it successfully sends the POST request.
Any idea why the same url would return a 404 error using native Javascript as opposed to AJAX?
Thanks
Sending AJAX request using POST method
var xhr = new XMLHttpRequest();
var url = "url";
var data = "email=hey#mail.com&password=101010";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(data);
Sending AJAX request using GET method
xhr = new XMLHttpRequest();
var url = "url?email=hey#mail.com&password=101010";
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
}
xhr.send();
To avoid unexpected requests to the server, it's a good practice to use encodeURIComponent() method on any user-entered parameters that will be passed as part of a URI.

xmlhttp request status 302

I am trying to write core java script application that can test and analyse the http request. I started with below code. Firebug net tab says 302 status error.
<script type="text/javascript">
$(document).ready(function(){
var req = new XMLHttpRequest();
req.open("GET","http://www.google.com",true);
req.onreadystatechange = statusListener;
req.send(null);
});
function statusListener(req){
if (req.readyState == 4)
{
if (req.status == 200) {
var docx=req.responseXML;
console.log(docx);
}
}
}
</script>
3xx status codes are redirections.
302 means "Found". Quote from w3.org:
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.
If you want to get the page it redirects to, you have to check the URI in the response headers with the getResponseHeader() method.
You can see here to see how to access the correct URI.

Categories

Resources