jquery Ajax (CORS) cross-domain Access interface

Source: Internet
Author: User

Today, the front-end debugging, because the interface is currently and front-end is not a machine, so the front end of the use of Ajax access interface needs to cross the domain;

Preparatory work:

1, the use is Cros

2, the front-end use of jquery Ajax;

3, back-end node + Express

Steps:

1, front-end configuration:

$.ajax (
    type: "POST",
    URL: "http://xxxxxx",
    dataType: ' JSON '
    data: {name: "John", Location: "Boston"}
    xhrfields:
        ' access-control-allow-origin ': ' * ' (
msg)->
    console.log "Data Saved:" + msg
    false
). Fail ((JQXHR, textstatus)->
    console.log "fail:" + Textstatus
    false
)

2, Back-end configuration:

Router.post ('/create ', function (req, res) {
    var db = req.db;
    Res.setheader (' Access-control-allow-origin ', ' * ');
    var user = {
        username: ' The reddest ',
        email: ' brandon@switchonthecode.com ',
        firstName: ' Brandon '
        , LastName: ' Cannaday '
    };

    var userstring = json.stringify (user);
    Res.send (userstring);
});

Summarize:

1, the front-end needs to specify DataType and Access-control-allow-origin

DataType: ' JSON '
data: {name: "John", Location: "Boston"}
xhrfields: '
       access-control-allow-origin ': ' *'
2, back-end needs to configure Access-control-allow-origin and results into JSON
Es.setheader (' Access-control-allow-origin ', ' * ');
var user = {
        username: ' The reddest ',
        email: ' brandon@switchonthecode.com ',
        firstName: ' Brandon '
        , LastName: ' Cannaday '
};

var userstring = json.stringify (user);

Reference:

1, HTTPS://DEVELOPER.CHROME.COM/EXTENSIONS/XHR

2, http://www.html5rocks.com/en/tutorials/cors/


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.