并非立即显而易见的是,服务器设置的cookie(至少在CORS请求中,并且可能(可能)在所有请求中)都被限制在与服务器相同的域中。
index.js(Node.js服务器)
const http = require('http');const fs = require('fs');// Pretty colorsconst colors = { purple: ' 33[95m', orange: ' 33[93m', blue: ' 33[97m', underline: ' 33[4m', bold: ' 33[1m', reset: ' 33[0m'}const server = http.createServer(function (req, res) { //Console logs to verify what's getting hit. console.log(colors.purple + colors.underline + 'Hit it!' + colors.reset); console.log(colors.orange + colors.bold + 'url:' + colors.reset, req.url); if (//cookie/.test(req.url)) { console.log(colors.blue + 'We need to cook(ie) Jessen' + colors.reset); // Generate a random string in a rather convoluted way. var randomStr = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36) + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36) + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36); randomStr = new Buffer(randomStr.toString(), 'binary').toString('base64'); // All .dev domains pointed to localhost via dnsmasq, though a hosts file // Update should also do the trick. res.writeHead(200, { 'Set-cookie': 'ajaxTestcookie=cookie' + randomStr + '; domain=.example.dev; HttpOnly', 'Access-Control-Allow-Origin': 'http://example.dev:3999', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type, Set-cookie, *' }); return res.end('OK!'); } console.log(colors.blue + 'We're having fun at the HTML!n' + colors.reset); // Send out html file. fs.readFile('./cookies.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Failure to launch!'); } res.end(data.toString()); });});server.listen(3999); // api.example.dev:3999, for examplecookies.html
<html><head> <title>cookie Test</title></head><body> <button >Get cookies!</button> <script> (function() { document.querySelector(".getcookie").addEventListener("click", function(e) { console.log("test"); var req = new XMLHttpRequest(); // Request succeeds, but cookie will not be set! // req.open("GET", "http://localhost:3999/cookie", true); // This line, however, will work, assuming this page is on // the same domain, or a subdomain of the same domain. // (For example test.example.dev and api.example.dev) // As long as the Access-Control-Allow-Origin Header is // properly set to allow the domain. req.open("GET", "http://api.example.dev:3999/cookie", true); req.onload = function() { console.log(req.responseText); }; req.withCredentials = true; req.send(); }); }()); </script></body>


