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