I have spring soap web service that works well. But my js client
var req = new XMLHttpRequest();
if(req.readyState == 4){....}
req.open('POST', 'http://localhost:8080/CurrencyService', true);
req.setRequestHeader("Content-Type", "text/xml");
req.send(msg);
throws
405 Method Not Allowed - http://localhost:8080/CurrencyService
How can I fix it?
I don't know anything about Spring WS, but apaprently whatever you have defined to handle /CurrencyService doesn't accept a POST. Skimming the docs I'd say your WebServiceMessageReceiverHttpHandler is missing or misconfigured.
Related
I'm currently coding a php website which reads certain values from a json file from my server.
Now when i request the xmlhttp request to my server, i get the Access-control-allow-origin ERROR in console. I already find out i have to set Access-control-allow-origin: *; in my Apache configuration but i don't want to use * because I don't want to give everyone access to my website. So how can i just give permission for one json file to every client?
var requestURL = 'https://myWebsite/blabla.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var response = request.response;
jackpot = response.items[0].value;
var inner = document.getElementById("myid");
inner.innerHTML = jackpot+" EURO";
this is my js code and i always get the Error, except i use Access-control-allow-origin: *, which i dont want to use because its unsave.
Please care im little new to web coding so im not really professional sorry.
In your PHP backend, allow only to your domain for Access-control-allow-origin not *. So that it will be safe.
I have code like:
jQuery.ajax({
url: url // Some URL
});
The above code worked perfectly. But, I have a requirement to convert this code to pure JS. So, I did:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
But, here when the AJAX request is fired I get this error in rails server log:
ActionController::InvalidCrossOriginRequest - Security warning: an
embedded tag on another site requested protected JavaScript.
If you know what you're doing, go ahead and disable forgery protection
on this action to permit cross-origin JavaScript embedding.
NOTE: I had faced similar error when I passed format: :js in link_to(Fix I referred). But, this happens with pure JavaScript code.
How do I fix this?
Adding xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); fixed the cross origin error in rails.
Now, the code looks like:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhttp.send();
I have been using postman to test an API which, I am successfully able to call.
When I try to execute this call through javascript I get an authentication error.
The URL and authorization match that of the postman call and when I call using these details with curl I am able to retrieve the correct data.
<script type="text/javascript">
var data = new FormData();
data.append("attributeId", "");
data.append("validFrom", "");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "http:/restpAPI/test");
xhr.setRequestHeader("authorization", "Basic asdsadsadjlafdkfjkldfj==");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "dsadasd-asdsad-asd-asd-aasd");
xhr.send(data);
</script>
When I run a local web page with this script I get a 401 saying Unauthorized.
What is the difference between the JavaScript code and postman or cURL and is there a way of authenticating from JavaScript?
Update
I have discovered that setting the RequestHeader with the authorization key turns the request from a get to an options. This is causing the error.
Although HTTP Headers are supposed to be case insensitive, have you tried setting the headers' names with title case (Authorization)?
I'm trying to build a webservice (Java based server and Javascript base client) I only need to send a Post request with json data and I need to get a post response with json data from server.Since client and server have different domains I think cors need to be supported. Up to now, I've implemented these: (My client implementaion is almost same with html5 rocs tutorial)
Web service client (js):
// I call client = new WSclient() in one of my js files
WSclient=function(){
makeCorsRequest();
}
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text;
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://localhost:8080/myapp/myfunction';
var xhr = createCORSRequest('POST', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.send();
}
Web service server (java)
#Path("/myapp/")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class myFunctionClass {
#POST
#Path("myfunction")
public Response recommendations(User inf){
// From the client I also need to send json
// like {"name":"john","surname":"smith","name":"marry","surname":"smith"}
// and if possible I want to put this infformation inside inf object
List<String> infos = inf.getInformation();
// here I call one of the my methods to get recommendations
// I remove it for simplicity and just put type of recommendations object
// list<Recommendation> recommendations= runFunction(infos);
final StringWriter sw =new StringWriter();
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(sw, recommendations);
System.out.println(sw.toString());
sw.close();
return Response.ok(sw.toString(), MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();
}
}
However, I think I need to do something more because when I run these, I got
XMLHttpRequest cannot load http://localhost:8080/myapp/myfunction.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
So what should I add to my server code to get rid of this error? Besides, how could I send json data inside my request in client? This is my first time dealing with such issues therefore, If my question a bit absurd, sorry about that.
EDIT
When I remove
xhr.setRequestHeader(
'X-Custom-Header', 'value');
part from the client, It works properly. As I said before, this is my first time with web-services and javascript so actually I dont know what does this line of code. Could anyone explain me what happens if it exists or not?
EDIT2
I understood that, I need to put
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
in order to send a json with request.But when I added this, same errors come back. What should I add to server to achive this ?
What's happening is that there is a preflight request (which is an OPTIONS request), made before the initial request. So you need an #OPTIONS endpoint to handle that request (i.e. set the response header). In your current code, you are trying to set it in the original requested endpoint response, where the OPTIONS request won't even reach.
A more common approach, instead of creating an #OPTIONS endpoint for each target, just use a Jersey filter as seen in this answer. The headers will get sent out for all request.
See Also:
HTTP access control (CORS)
EDIT
Example #OPTIONS
#OPTIONS
#Path("myfunction")
public Response cors() {
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD")
// whatever other CORS headers
.build();
}
I'm working on a Chrome extension and I've some issue with a XHR cross-domain. Let me explain: I set right permission in manifest.json for a domain and I make (in my js file) a simple XMLHttpRequest. Request works fine but responseXML field is null. Why? It is not an issue with SOP and responseText correctly contains HTML text of the page requested. How I can parse it? I can't do it with DOMParser().parseFromStringeven with using https://developer.mozilla.org/en/DOMParser implementation, I receive everytime a single.
Some suggestions? My (simple) code is following:
var req = new XMLHttpRequest();
req.open("GET", "http://somedomain.com", true);
req.overrideMimeType("text/xml");
req.setRequestHeader("Content-Type", "text/xml");
req.onload = anonymousFunction;
req.send(null);
Thanks for any replies!