How to solve the problem of XMLHttpRequest cross-origin request

Source: Internet
Author: User

In web development, cross-origin requests are a common problem and there are many solutions. Here we recommend a lightweight cross-origin solution for XMLHttpRequest requests.

If you don't talk about it, read the code directly:

The client initiates a cross-origin request:

Anhttprequest = new XMLHttpRequest ();


Anhttprequest. onreadystatechange = function (){
If (anhttprequest. readystate = 4 & anhttprequest. Status = 200 ){

// Handle your response here when it's successful.
Acallback (anhttprequest. responsetext );

}

Anhttprequest. Open ("get", "http://anotherdomain.com/testApi", true );
Anhttprequest. Send (null );

 

On the server side, we need to set this origin to be allowed. The Code is as follows:

The simple method is as follows:

Response. addheader ("access-control-allow-origin", "http: // origindomain: 801 ");
Response. Write ("CORS test successful! ");

 

Because nodejs is used on the server and express middleware is used, the actual code is similar to this:

// Module dependencies.
VaR application_root = _ dirname,
Express = require ('express ');

// Create server
VaR APP = Express ();

App. All ('*', function (req, res, next ){
If (! Req. Get ('origin '))

Return next ();


// Use "*" here to accept any origin
Res. Set ('access-control-allow-origin', 'HTTP: // origindomain: 100 ');
Next ();
});

 

Does it seem easy?

How to solve the problem of XMLHttpRequest cross-origin request

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.