Nodejs+expressjs Resolving Cross-domain Requests Cors

Source: Internet
Author: User

http://blog.csdn.net/baby97/article/details/50329491


Although the front-end has a variety of ways to deal with Cross-domain, but more than fine, the shortcomings are more obvious. A relatively better way is to get involved with the back end, which is not only more adaptable, but also a front-end that sends a normal AJAX request. This technique is called cors.

Cross-origin Resource sharing Cross-domain resource sharing should be considered the most recommended cross-domain processing scenario. Not only for all kinds of method, but also more convenient and simple. Of course, the only thing that hangs like this is the modern browser support, IE8 the old relic. .

var express = require (' Express ');
var app = Express ();
Sets the Cross-domain access to this
app.all (' * ', function (req, res, next) {
    Res.header ("Access-control-allow-origin", "*") before other settings. ;
    Res.header ("Access-control-allow-headers", "X-requested-with");
    Res.header ("Access-control-allow-methods", "put,post,get,delete,options");
    Res.header ("x-powered-by", ' 3.2.1 ')
    res.header ("Content-type", "Application/json;charset=utf-8");
    Next ();
});

App.get ('/auth/:id/:p assword ', function (req, res) {
    res.send ({id:req.params.id, name:req.params.password});
}) ;

App.listen (3000);



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.