Implement Cors cross-domain with Express (top-simple request)

Source: Internet
Author: User

Today, a cross-domain request for logon verification has been encountered. So there's an opportunity to try cross-domain.

The specific scenario is that a login interface is written on the site called CAs, but the relevant login authentication background interface is written in the site called Earth.

The first response is to use JSONP, but JSONP can only get requests, and once the cross-domain will have a permissions problem (this will say), the main thing is jsonp kind of similar hack style always makes me feel awkward. Of course, the main thing is that the backstage with STRINGMVC has achieved cors.

Cors is a way of sharing cross-domain resources, and Ajax is actually no different, and the relative restful methods are all right, and there are differences in how they are implemented.

This time first summed up the relatively simple, with get send an email address, let the background verify whether the mailbox is available, return True or false.

First write a client, this client is the default way Webstorm, the domain name should be localhost:63342

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Title</title></Head><Body><ButtonID= "Cors">Send Cors</Button></Body><Script>    varcors=Document.queryselector ('#cors'); Cors.onclick=function () {        varXHR=NewXMLHttpRequest (); Xhr.open ('GET','Http://localhost:3001/getName',true); Xhr.withcredentials=true; Xhr.onload=function(data) {Console.log (data);        }; Xhr.send (NULL); }</Script></HTML>

This page is a click of a button to send a GET request to port 3001, you can see in addition to Xhr.withcredentials=true, and Ajax is no different, cors is basically a service-side technology. In addition, in the elevation of three said the need to write a origin:xxxx on the request header to tell the server of your source information, but in fact, I found that even when the test is not written, the browser will automatically add this sentence to the request.

var express=require (' Express ');
var url=require (' url ');
var app=express ();
var allowcrossdomain = function (req, res, next) {
Res.header (' Access-control-allow-origin ', ' http://localhost:63342 ');
Res.header (' access-control-allow-methods ', ' get,put,post,delete ');
Res.header (' access-control-allow-headers ', ' content-type ');
Res.header (' Access-control-allow-credentials ', ' true ');
Next ();
};
App.use (Allowcrossdomain);
App.get ('/checkemail ', function (Req,res,next) {
var queryvalue=url.parse (req.url). query;
if (queryvalue=== ' [email protected] ') {
Res.send (TRUE);
}else {
Res.send (FALSE);
}

});
App.listen (3001);

Can see the obvious difference is a allowcrossdomain middleware, the role of this middleware is to write something to the response head.

Why is the response header? Here is a little understanding of me, not welcome correction:

Cross-domain requests need to be handled because of the same-origin policy, where the protocol, domain name, and port must be identical to initiate a request. The same-origin policy is actually browser behavior, because cross-domains that do not restrict are more dangerous, so each browser does cross-domain restrictions. For Cors, a pre-request is sent to the server, and the service side writes back the response header. The browser discovers that a pre-requested response header is allowed to send the request itself before the real request is sent.

The following sentence is to tell what site is allowed

Res.header (' Access-control-allow-origin ', ' http://localhost:63342 ');

The browser will know that the server is allowing cross-domain access to the site. In fact, this is a white list mechanism.

What other three is the meaning of Baidu under the good. A little mention, it is recommended to write on the client xhr.withcredentials=true; A corresponding response header is also added to the corresponding service side. However, Access-control-allow-origin can not write * to allow all site requests, in actual engineering also rarely allow all sites. This is also jsonp bad place, if you want to set the request permission to consider using other methods, not as easy as cors.

Of course, all that is said is a simple request for cors. Head GET Post method, using some of the request headers (well, sending JSON is sure to be OK) is a simple request.

The mechanisms for complex requests are not the same as simple requests, so write down the next detailed instructions.

Implement Cors cross-domain with Express (top-simple 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.