AJAX request returning "405 Method Not Allowed" - javascript

I'm trying to write a submit form that sends a JSON object to an application on another server but I keep getting a 405 Method Not Allowed error in the console.
The app is set up to accept POST and that's what I'm sending so I'm lost at where the error is. There is also a warning in the console Loading failed for the <script> with source "Request URL"
Is this a problem with the way the application is reading the JSON or the format the JSON is being sent in?
From the app server
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
Code
json = JSON.parse(string);
$.ajax({
type: 'POST',
dataType: "jsonp",
contentType: "application/json",
url: "http://test:8080/request/committee",
data: json,
cache: false,
success: function (response) {
$("#successModal").modal('show');
},
failure: function (response) {
$("#failureModal").modal('show');
},
error: function (response) {
$("#failureModal").modal('show');
}
});
e.preventDefault();//prevents the form from being submitted by default
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: test:8080
Referer: http://www.form.com/servlet/rsvp.jsp?location=110%20Road%20Bolton%20Landing,%20NY&purpose=%20TPAS%20Teleconference%20(RSVP%20here%20to%20attend%20in-person)&visitDate=2018-03-15&visitStartTime=6:00%20AM&visitEndDate=7:00%20AM&committee=all
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0
Response Headers
HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Connection: keep-alive
Content-Length: 0
Date: Mon, 16 Apr 2018 15:38:24 GMT
Edit: corrected contentType. Same error occurs

From your exception details , it seems to be
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
either you are passing invalid content type or not passing at all , I see your content type is application/jsonp.
just give a try with application/javascript.

This error happened to me once. My java method wanted xml not json. this annotation (in java) fixed it for me.
#Consumes(MediaType.APPLICATION_JSON)
I hope this helps!

Related

In PhoneGap App, AJAX call error event gets triggered even the server returns 200 OK status

I am using the below Ajax call to connect with Spring security from crossdomain (PhoneGap). The response I got is 200 OK - it has the expected response in JSON format. But the error event is getting fired due to CORS. On the Spring side, I have added a CORS filter to allow any type of URL (Access-Control-Allow-Origin = ' * ').
$.ajax({
type:'POST',
url: CONTEXTPATH + '/j_spring_security_check',
data: formData,
dataType: 'text json',
cache: false,
crossdomain: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With' : 'XMLHttpRequest',
},
success: function(data) {
},
error: function(data) {
}
});
The response in the browser console is:
POST XHR http://192.168.0.20:8080/startupbay/j_spring_security_check [HTTP/1.1 200 OK 260ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.0.20:8080/startupbay/j_spring_security_check. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
The request and response headers are:
RESPONSE HEADER:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, x-requested-with, Origin, Accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD
Access-Control-Allow-Origin:*
Access-Control-Max-Age:86400
Access-Control-Request-Headers:x-requested-with
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date: Thu, 23 Feb 2017 06:14:39 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
REQUEST HEADER:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.5
Access-Control-Request-Headers:x-requested-with
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.0.20:8080
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
origin:http://192.168.0.20:3000
In the Error section, I looked for the error mentioned in 'xhr'. The statusText:error, responseText:'', status:0.
Please help me in resolving this issue.
When I set the crossdomain:true, that time in the browser console I can see only the OPTIONS request, but not followed by the POST request.
Just to add, this issue is appearing only for the '/j_spring_security_check' URL. For another URL, the same type setup is working fine.

Echo posted Ajax data

I am using AJAX to post some array data to the server. I get the following expected results in the Firebug network console from the Ajax request.
POST -----> http://example.com/drag_data.php
//request header
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://example.com/drag.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 90
Cookie: PHPSESSID=b1lr9he4l2hbcnlkcsebfq2134
Connection: keep-alive
//data in the request body
item[]=1&item[]=3&item[]=2&item[]=4&item[]=5
//firebug params
item[]:"1"
item[]:"3"
item[]:"2"
item[]:"4"
item[]:"5"
for infor this is the ajax call which give the expected success message (same as the firebug param output)
$.post({
data: data,
type: 'POST',
url: 'drag_data.php?',
success:function(result){
$(".result").html(data);},
error: function(){
console.log(arguments);
}
});
I just want to echo the posted data in the drag_data.php script. I have tried the following test code (as well as (print_r and var_dump) but cannot see any posted data which has baffled me. Can anyone tell me what I am doing wrong please?
drag_data.php test file
$i = 0;
//this loop is failing to echo the posted array data from the Ajax request
foreach ($_POST['item'] as $value) {
echo "each".$value;
$i++;
}
?>
Make url: '/drag_data.php', with preceding slash and without ?.
Maybe serializing will help: make data: JSON.stringify(data) on client and json_decode on server.
Check configurations of your server - are requests you're seeing in your firebug actually reaching the server?
Finally cracked it. Turns out that there was a server side issue with Ajax calls that has now been resolved by the service provider. So in actual fact my original code works as it should. Maybe this thread or the code will be useful for someone else in the future.

jQuery & CORS always fail on an open remote server

I'm trying to simulate a POST, with jQuery $.ajax() method, on a remote server which is supposed to have CORS enabled.
The idea is to submit a form with username/password provided and get the cookie delivered by the server from a successful authentication.
Here is the jQuery:
$.ajax({
type: 'POST',
crossDomain: true,
async: false,
url: this.url,
data: {
username: this.username,
password: this.password
},
xhrFields: {
withCreditentials: true
},
success: function(responseData, textStatus, jqXHR) {
console.info(jqXHR.getAllResponseHeaders());
},
error: function(responseData, textStatus, errorThrown) {
console.warn(errorThrown);
}
});
Here is the response headers:
HTTP/1.1 200 OK
Connection: close
Content-Type: text/html
Pragma: no-cache
Cache-control: no-cache,max-age=0,must-revalidate
Content-Encoding: gzip
Vary: Accept-Encoding
Transfer-Encoding: chunked
And the request headers:
Accept: * / *
Accept-Encoding: gzip, deflate, sdch
Accept-Language: fr,en-US;q=0.8,en;q=0.6
Cache-Control: max-age=0
Connection: keep-alive
Host: my remote server (URL is hidden)
The problem is that I get a console.warn telling me:
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'URL'
I also tried with a Chrome extension which simulate a POST: I put the same data as in my jQuery and everything succeed, from the call to the cookie delivered once the form is submitted.
I don't understand how my jQuery fails to load the URL but is giving me a 200 OK anyway! And I don't understand how to make it right!
Where I'm doing a mistake?
It would appear that you need to add the Access-Control-Allow-Origin: * header to the api response header. Your REST client (the chrome extension) doesn't abide by CORS rules like the browser, which is why it works.

ngResource PUT returns bad request due to $promise and $resolved in the JSON object

I've been struggling with this problem for the last few hours, and every tutorial points toward the solution that I have implemented but it doesn't work.
Basically my PUT request returns an error:
PUT http://localhost:8083/stockapi/rest/stocks/5485cba248673a0dd82bb86f 400 (Bad Request)
When I intercept the request, I see that it contains a $promise and $resolved data element:
> {"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXX","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
This makes sense since I'm using the ngResource object -- but every tutorial shows that the following code should be able to handle it, but it doesn't.
Note/edit: if i PUT the JSON object without the "$promise" and "$resolved" elements through an external program (such as Postman REST client) then it works fine.
Factory:
.factory('Stock',function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
}); });
Controller (note: doing 4 updates but none of them work, 4 times the same Bad Request):
.controller('StockEditController',function($scope,$log,$http,$state,$stateParams,Stock){
$scope.stock = Stock.get({id:$stateParams.id});
$scope.updateStock=function(stock) {
Stock.update(stock);
stock.$update();
Stock.update($scope.stock);
$scope.stock.$update();
$state.go('stocks');
};
});
I'm really clueless right now how to use the ngResource object in the correct way so that I can use it to put/post to my webservice. Any ideas?
Thanks!
EDIT:
Chrome network output:
Response header
Remote Address:[::1]:8080
Request URL:http://localhost:8080/stockapi/rest/stocks/5485cba248673a0dd82bb86f
Request Method:PUT
Status Code:400 Bad Request
Request Headersview parsed
PUT /stockapi/rest/stocks/5485cba248673a0dd82bb86f HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 355
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/stockapi/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Request Payloadview parsed
{"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXXYYY","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
Response Headersview parsed
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Date: Tue, 09 Dec 2014 06:36:24 GMT
Connection: close
According to the docs you are not quite using the update action correctly.
So really your updateStock method should be:
$scope.updateStock=function(stock) {
Stock.update({id: stock.id}, stock);
Stock.update({id: $scope.stock.id}, $scope.stock); //not sure why you have 2 calls here
$state.go('stocks');
};
Just looking at the factory definition and how it differs from mine, you should change that second parameter of factory definition into array to something like this:
.factory('Stock',[$resource, function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
});
}]);
Not sure if this is the issue but that is at least significantly different to angular docs' definition on dependency injection here: https://docs.angularjs.org/guide/di
If not, could you also print out the contents of $scope.stock after the GET returns the data there?
I know this question is super old, but I stumbled upon the same issue and found this SO question as well as this question:
http://www.scriptscoop2.com/t/fddc3f0a1f6f/angularjs-using-ngresource-for-crud-adds-extra-key-value-when-using-save.html
There was 1 answer which explained that the issue is coming due to CORS (cross origins). Which means that your server side needs to allow it. If you are using Spring MVC it would be enough to add the org.springframework.web.bind.annotation.CrossOrigin annotation at the controllers request mapping:
#CrossOrigin
#RequestMapping(value = "/product/{id}", method = RequestMethod.POST)
#ResponseBody
public void editProduct(#PathVariable("id") final long id, #RequestBody final ProductDto productDto) {
// your code
}

jQuery PUT ajax request not working

I'm trying to save a Backbone model in couchdb so I've overridden the save method with a ajax requet to couchdb:
$.ajax({
type: 'PUT',
url: 'http://127.0.0.1:5984/movies/' + this.get('id'),
contentType: 'application/json',
data: JSON.stringify(this.toJSON()),
success: function() {
console.log('asdf');
},
failure: function() {
console.log('test');
}
});
The request is sent but when I look at the couchdb log jQuery seems to send a OPTIONS HTTP method instead of PUT:
[info] [<0.1601.0>] 127.0.0.1 - -
'OPTIONS' /movies/862 405
and couchdb sends a 405 HTTP Response code (method not allowed). Any Ideas?
Edit
Here are the headers sent to CouchDB:
OPTIONS /movies/862 HTTP/1.1
Host: 127.0.0.1:5984
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://localhost:8888
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
There's a backbone connector for couch-db.. https://github.com/janmonschke/backbone-couchdb
PUT isn't supported by all browsers. Also, the property for your data is "data", not "body".

Categories