cookie没有设置在跨域 - angularjs和nodejs / express

时间:2015-03-25 08:39:47

标签: angularjs node.js cookies cross-domain

未在跨域请求上设置cookie。我的服务器在localhost:8000中运行,客户端在localhost:9000中运行。服务器nodejs / express上的cors设置是

app.use(function(req, res, next) {
console.log(req.method);
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Authorisation");
if (req.method === 'OPTIONS') {
    return res.send(200);
} else {
    return next();
}});

Angualarjs用于客户端,而cors配置为

SelappsAdmin.config(['$httpProvider', function($httpProvider) {
  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])

2 个答案:

答案 0 :(得分:2)

快递

app.use(require('cors')({
  origin: function (origin, callback) {
    callback(null, origin);
  },
  credentials: true
}));

on angular

$httpProvider.defaults.headers.common['X-Requested-With'] ='XMLHttpRequest';
$httpProvider.defaults.withCredentials = true;

答案 1 :(得分:1)

快递

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: 'yoursecret',
    cookie: {
        path: '/',
        domain: 'yourdomain.com',
        maxAge: 1000 * 60 * 24 // 24 hours
    }
}));
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

on angular

$httpProvider.defaults.withCredentials = true;

delete $httpProvider.defaults.headers.common["X-Requested-With"];

我从Link

中找到了
相关问题