Ajax--cors cross-Domain calling rest API FAQs and settings for the front and back end

Source: Internet
Author: User

The restful architecture is one of the most popular Internet software architectures, where the backend interface can be shared between the browser front end and the mobile phone.

But it involves the JS cross-domain call interface is always a headache, the following will follow the Chrome error message together to solve.

Assumption: The front-end domain name is front.ls-la.me , the backend domain name is api.ls-la.com . The front end needs access to the interface http://api.ls-la.com/user/info.json , which needs to be accessed by a GET method.

Now, using AJAX to send a request to the back end, get the first error. (For a cors cross-domain reference: http://blog.csdn.net/fdipzone/article/details/46390573)

Error 1:
XMLHttpRequest cannot load Http://api.ls-la.com/user/info.json. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' http://api.ls-la.com ' is therefore not allowed access.

Tip The response header does not have Access-Control-Allow-Origin this, Google learned that the server needs to specify which domain name can access the backend interface, set:

Header (' access-control-allow-origin:http://front.ls-la.me '); // If you are not afraid of the deduction of wages can be set: Header (' access-control-allow-origin: * ');

Send the request again, and error.

Error 2:
XMLHttpRequest cannot load Http://api.ls-la.com/user/info.json. Request header field X-requested-with is not allowed by Access-control-allow-headers in preflight response.

This means that there is this field in the AJAX header message, which is X-Requested-With not allowed on the backend. Let's allow it:

Header (' Access-control-allow-headers:x-requested-with ');

OK, this is not an error, but careful analysis of the request process, found that the browser sent to the interface address two requests, the first is the OPTIONS way, the second is the GET way.

The first request here is called "preflight table request (pre-check form requests, Microsoft so translated, do not know right)". This request is initiated by the browser on a cross-domain basis, and the function is to ask for a look at the server support that does not support current access. If not, the errors listed previously are reported, and if supported, a normal GET request is sent, and the corresponding data is returned.

But before each request, you have to have the options, and as a typical Virgo, you can't tolerate it. Need to tell the browser that you have to make a point, it is not fun to do this old:

// tell the browser I support these methods (back-end unsupported methods can be removed from here, of course, you can also add the options method behind ...) )header (' Access-control-allow-methods:get, PUT, POST, DELETE '); // tell the browser I already remember you, do not send the options request header (' access-control-max-age: '. 3600 * 24) within one day

Okay, here's the thing.

It's weird!

Suddenly one day the test girl came to tell you that the site can not remember the user's state, a check found across the domain when the cookie expired.

Error 3:

JS when sending cross-domain requests, the request header is not with the cookie, need to let him carry:

1 //JS2 varXHR =NewXMLHttpRequest ();3Xhr.open (' GET ', ' Http://api.ls-la.com/user/info.json ');4Xhr.withcredentials =true;5Xhr.onload =Onloadhandler;6 xhr.send ();7 8 //JQuery9 $.ajax ({TenURL: ' Http://api.ls-la.com/user/info.json ', One xhrfields: { AWithcredentials:true -     }, -Crossdomain:true, the }); -  - //Angular three Choice one -$http. Post (URL, {withcredentials:true, ...}) +$http ({withcredentials:true, ...}). Post (...) -App. Config (function($httpProvider) { +$httpProvider. defaults.withcredentials =true; A}

All in all, just set it up in the XHR withCredentials = true and then cross-domain requests to bring a cookie. Note that the cookie here follows the same-origin policy, which is that the cookie sent by the backend belongs to the domain name api.ls-la.com .

Send a POST request with a cookie that still has an error:

Error 4:
XMLHttpRequest cannot load Http://api.ls-la.com/user/info.json. Request header field Content-type is not allowed by Access-control-allow-headers in preflight response.

As with the above X-Requested-With error, the header information is not allowed, the backend changed:

Header (' Access-control-allow-headers:x-requested-with, Content-type ');

Again, or an error:

Error 5:
XMLHttpRequest cannot load Http://api.ls-la.com/user/info.json. Response to preflight request doesn ' t pass access control Check:credentials flag was ' true ', but the ' Access-control-allow -credentials ' header is '. It must is ' true ' to allow credentials. Origin ' http://front.ls-la.me ' is therefore not allowed access.

It is obvious that the back-end code adds a line that allows cookies to be accessed:

// allow the front end with a cookie to access the header (' access-control-allow-credentials:true ');

Summarize

Execute the following function before the backend program loads to avoid wasting system and database resources on the options request.

function Cors_options () {    header (' access-control-allow-origin:http://front.ls-la.me ');    Header (' access-control-allow-credentials:true ');     if return ;    Header (' Access-control-allow-headers:x-requested-with, Content-type ');    Header (' Access-control-allow-methods:get, PUT, POST, DELETE ');    Header (' Access-control-max-age: '. 3600 *);    Exit;}

Reference:
Pre-check Table request
Cross-origin Resource Sharing
Angular cross-domain scenarios with cors note the [cors classification] section here.

Ajax--cors cross-Domain calling rest API FAQs and settings for the front and back end

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.