Error 405: Method not allowed - javascript

I have my json data which i need to be posted to a url or just update the json data in one of my site urls. But i get the 405 error.
This is my code.
$.post("details", {name: "John", location: "us"});

405 errors can be traced to configuration of the Web server and security governing access to the content of the Web site. It seems that the server to which you are sending the Post request(your Site's server) has been configured to block Post request. You can configure your server to allow the Post request. For more details, go to http://www.checkupdown.com/status/E405.html

I had the same problem. My failure was in the sort of the request:
I had a "POST" request in my mockserver.js:
{method: "POST", path: "app/Registration/sendRegisData.*", response: function (xhr) { xhr.respondFile(200, {}, "../testdata/getUser.json"); } }
and tried to use this path with a "PUT"-call in my controller:
$.ajax({
url: "z_dominosapp/Registration/sendRegisData",
type: "POST",
data: data
}).done(function(){.......});
First, I didn't noticed it and was wondering why only the "fail" part of the ajax call was called. Maybe this careless mistake of me helps you in any way.

Related

How to send client side cookies (javascript) to server side (node.js) using Microsoft Bot Framework Directline API? [duplicate]

I am working on an internal web application at work. In IE10 the requests work fine, but in Chrome all the AJAX requests (which there are many) are sent using OPTIONS instead of whatever defined method I give it. Technically my requests are "cross domain." The site is served on localhost:6120 and the service I'm making AJAX requests to is on 57124. This closed jquery bug defines the issue, but not a real fix.
What can I do to use the proper http method in ajax requests?
Edit:
This is in the document load of every page:
jQuery.support.cors = true;
And every AJAX is built similarly:
var url = 'http://localhost:57124/My/Rest/Call';
$.ajax({
url: url,
dataType: "json",
data: json,
async: true,
cache: false,
timeout: 30000,
headers: { "x-li-format": "json", "X-UserName": userName },
success: function (data) {
// my success stuff
},
error: function (request, status, error) {
// my error stuff
},
type: "POST"
});
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
I agree with Kevin B, the bug report says it all. It sounds like you are trying to make cross-domain ajax calls. If you're not familiar with the same origin policy you can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript.
If this is not intended to be a cross-domain ajax call, try making your target url relative and see if the problem goes away. If you're really desperate look into the JSONP, but beware, mayhem lurks. There really isn't much more we can do to help you.
If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.
In production this error will not happen, since the request and the api will be in the same domain.
I hope it helps!
As answered by #Dark Falcon, I simply dealt with it.
In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.
So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:
app.use(function(req, res, next) {
if (req.method !== "OPTIONS") {
if (req.session && req.session.id) {
// Session exists
next();
}else{
// Create session
next();
}
} else {
// If request method is OPTIONS, just skip this part and move to the next method.
next();
}
}
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Consider using axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});
I had this issue using fetch and axios worked perfectly.
I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.
Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.
$.ajax({
url: '###',
contentType: 'text/plain; charset=utf-8',
async: false,
xhrFields: {
withCredentials: true,
crossDomain: true,
Authorization: "Bearer ...."
},
method: 'POST',
data: JSON.stringify( request ),
success: function (data) {
console.log(data);
}
});
the contentType: 'text/plain; charset=utf-8', or just contentType: 'text/plain', works for me!
regards!!

Request header values not send? CORS - jQuery Ajax

Im trying to make a request from one application to another. So i created some headers which are required by my application and filled them in for the Ajax Request. Here is my code:
$.ajax({
method: 'GET',
url: 'http://my-domain.com/apps/filters/get-filters',
beforeSend: function(request){
request.setRequestHeader("X-Webshop-Domain", window.location.host);
request.setRequestHeader("X-Language", $('html').attr('lang'));
request.setRequestHeader("X-Request-Protocol", window.location.protocol);
request.setRequestHeader("X-Api-Version", '2');
},
headers: {
"X-Webshop-Domain": window.location.host,
"X-Language": $('html').attr('lang'),
"X-Request-Protocol": window.location.protocol,
"X-Api-Version": '2',
},
data: {}, success: function ( response )
{
}
});
Now when i load a page, this method is called but no response given. It gives me the "Header not allowed" issue. But when i check in my network tab (developer tools Chrome) i see my request, i see some headers but none of those. Does anybody has a idea how this is possible or what im doing wrong?
In case of CORS (cross domain requests), only basic headers are allowed. You will need to add the headers you wish to send to the server's response header:
Access-Control-Allow-Headers: X-Webshop-Domain, ...
Here's a related question you may find useful: Ajax Request header field Key is not allowed by Access-Control-Allow-Headers

No 'Access-Control-Allow-Origin' header error yet the POST goes through anyway

So, I have this JavaScript function, that does a simple jQuery AJAX() request:
function impLeads() {
var go_health_id = $(".sync-action").data("subscriber");
var customer_number = $(".sync-action").data("customer-number");
var lead_type = $(".sync-action").data("lead-type");
var person = {
lead_type: lead_type,
customer_number: customer_number,
subscriber_id: go_health_id,
first_name: "Daniel",
last_name: "Endo",
phone: "(937) 555-5555"
}
$.ajax({
type: "POST",
crossDomain: true,
dataType: "json",
data: person,
url: "https://www.brokeroffice.com/leads/leadImport.do",
cache: false,
success: function(html) {
$(".debug").show().html(html);
console.log('Leads imported for ' + go_health_id);
}
});
}
Now... this is a HTTP post to BrokerOffice.com. Lead data can be imported to BrokerOffice via HTTP POST. The Endpoint URL = https://www.brokeroffice.com/leads/leadImport.do. I am executing this script from http://mycompanysite.com/leads/. Notice that they have https:// and www while mine do not.
However, when I go into BrokerOffice.com, I see that the lead was successfully posted into their database so... despite this warning:
XMLHttpRequest cannot load https://www.brokeroffice.com/leads/leadImport.do. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mycompanysite.com' is therefore not allowed access.
The request went through.
The problem is that I have to this request on loop more than once so that JavaScript error will stop the loop from continuing the execution.
What can I do?
That header just stops you from being able to see a response from the server (not from sending a request).
The problem is that I have to this request on loop more than once so
that JavaScript error will stop the loop from continuing the
execution.
What can I do?
What can you do? The response header from the server needs to be changed to allow cross-origin communication. If you don't have access to changing the server, then you might be out of luck.
As #apsillers mentioned, you can send requests and they'll get there. You just can't get responses.
If you need to read the response, you can:
Use a light CORS proxy like https://github.com/gr2m/CORS-Proxy on your server.
Use a hosted proxy like http://crossorigin.me/

Cross Origin ajax "POST" request failing

I have a webservice(REST) running on localhost:8080, to call the webservice I use this jquery code:
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/user/register",
data: '{"name": "' + name + '","email": "' + email + '","password": "' + password + '"}',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType:"jsonp",
Accept : "application/json",
contentType: "application/json",
success: registerUser_success_callback,
error: registerUser_error_callback
});
When I try to call this javascript from the same domain(i.e. localhost:8080), it work just like a charm!. Here is the screen shot of the same:
But when I try to access the same from a different domain(i.e localhost:80), it fails, and surprisingly instead of a POST, it sends out a GET and I also get a log in my server's log file, saying that the GET method not supported for REST resource. Here is the screen of the same:
From what I have read on internet(especially here, great article!), cross domain request should first send out an OPTIONS request(which is cached for later usage.) What is going wrong in my case?
I have tried calling the rest service with same parameters using FireFox's plugin RESTClient, I was able call the rest service(POST method) successfully, so this mostly is the issue with ajax part.
Help me resolve this cors hell! and do lemme know if I need to share any more details on this.
PS: After #A. Wolff Suggested, I changed the data tyoe from jsonp to json, now my browser sends out OPTIONS, but after that it doesn't send the actual POST request!!!
Well, some more digging and I found the solution to this!
After the change A. Wolff suggested, browser was sending out an OPTIONS request and was receiving a 200 response, but after that actual POST request was not being sent to the server.
Problem was, if you send any specific headers, "Content-Type" in my case, server has to add that header in "Access-Control-Allow-Headers" field of the response(response of OPTIONS request). I changed my server side code to populate that field in the response header, and VOILA!
Hope this will be helpful to others, too!
Happy Coding.

POST 405 (Method not allowed) when trying to post AJAX request - Laravel 4

I am trying to issue a simple AJAX request to populate a menu in Laravel, however, I am having a lot of trouble with getting it to work properly.
I am not sure what the issue is, and after a couple hours of searching, I cannot find anything that can help.
Here is my AJAX request:
$.ajax({
type: 'POST',
url: '/ajax/populateApiAuth',
data: json,
dataType: 'JSON',
success: function (json) {
alert('test');
return true;
},
error: alert('fail')
});
My route to the AJAX callback:
Route::get('/ajax/populateApiAuth', 'ApiController#populateApiAuth');
and my controller to handle the AJAX callback in ApiController:
public function populateApiAuth()
{
return Response::json(array('msg' => 'test');
}
When sending the AJAX request, it returns with the fail message in the error parameters, and in the console, it tells me:
POST http://localhost:8000/ajax/populateApiAuth 405 (Method Not Allowed)
Researching this error message, it results from making a POST request to a different domain/server? How can this be?
I have tried to use an absolute URL for the AJAX request with:
url: '{{ URL::to("ajax/populateApiAuth") }}
which gives the full URL: http://localhost:8000/ajax/populateApiAuth but that does not solve the issue either.
Wouldn't this be your issue?
Route::get('/ajax/populateApiAuth', 'ApiController#populateApiAuth');
You set the route up for GET requests, but you're trying to access it via a POST request.

Categories

Resources