简体   繁体   中英

AJAX cross domain request to public API

I'm trying to set a POST via an AJAX call to register some basic data from a webpage. This is supposed to be a public web service so the request can be sent from any domain, by including a JS script.

However when executing the request i got an error :

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxxxxx' is therefore not allowed access. The response had HTTP status code 422.

The server response is set with the following :

response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    response.headers['Access-Control-Request-Method'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

And here is the JS request :

var params = "f="+_.open+"&t="+_.t0;
xmlhttp.open("POST",TRACKURL,true);
xmlhttp.send(params);

I guess something is missing in the request but i can't find how to fix it.

If you have idea, i'd be happy to hear it.

thnaks

i think this might help you, there is a example of how to do cross domain request

https://stackoverflow.com/a/17875201/2043592

I finally found an answer to my problem, if this can help anyone else : Actually the browser send a OPTIONS request before the POST request so in order to create a cross domain AJAX request you need to set headers in both the POST response and the OPTIONS response. This can be done in your application or in the web server configuration.

您需要在客户端上使用XMLHttpRequest2或XDomainRequest(IE)对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM