简体   繁体   中英

How to add cookie in cross domain xhr call from client?

For example if I have a cookie from domain A and my javascript client code is in domain B . Does browser auto pass the cookie of domain A to the request when I do an ajax request from domain B to domain A ?

Is there a setting I should add to set the cookie? It seems like my javascript client does not have access to domain A cookies.

For reference I am using this library https://github.com/naugtur/xhr

Use withCredentials:true .

This allows the cookies from remote domain to be passed back and forth assuming the correct access control headers are set at remote end point to allow "withCredentials"

Reference: XMLHttpRequest.withCredentials

You're looking for the withCredentials setting of your XHR library.

So:

var xhr = require("xhr")

xhr({
    withCredentials: true, // <--- this!
    method: "post",
    body: someJSONString,
    uri: "/foo",
    headers: {
        "Content-Type": "application/json"
    }
}, function (err, resp, body) {
    // check resp.statusCode
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM