当我尝试从端口3000获取它们时,为什么我的cookie和signedCookies在请求中为空?

时间:2019-05-15 12:34:16

标签: node.js express session-cookies

我想从带有express的get请求中检索会话cookie时遇到问题。

我的服务器在端口8000上运行,我的服务器在端口8000上运行。

当我直接进入http://localhost:8000/setcookie和/ getcookie时,我可以获取并设置cookie,它可以正常工作。 另一方面,当我尝试使用http://localhost:3000中的相同内容并使用axios在8000端口上获取或发布请求时,cookie和signedCookies在请求中为空,我不知道为什么。是因为即使我正在侦听并将请求发送到端口8000时,还是从3000端口发送它的?

我尝试使用get和post方法创建cookie。他们似乎都没有工作。我有点迷路了。

我希望我的解释很清楚,非常感谢!

服务器

const app = express()
const port = process.env.PORT || 8000
app.set("port", port)

const http = require('http').Server(app);

//Body Parser
var urlencodedParser = bodyParser.urlencoded({
    extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json());

//Définition des CORS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(cookieParser("secret")); 

app.get('/setcookie', function (req, res, next) {
  // Update views
  console.log("connection", req);
  var mail = req.body.email
  res.cookie('b', 'jefaisuntest', {signed: true, expire : 600000});

  // Write response
  res.send("cookie sent")
})

app.get('/getcookie', function(req, res) {
    var username = req.signedCookies['b'];

    console.log("iciiii", req)
    if (username) {
        return res.send(username);
    }

    return res.send('No cookie found');
});

const server = http.listen(port, function () {
    console.log(`listening on *:${port}`)
})

客户

import axios from 'axios';

const headers = {
    'Content-Type': 'application/json'
}
const burl = "http://localhost:8000"

export default {
    login : function(email:string, password:string) {
        axios.get(burl + '/setcookie')
    },
    isAuth : function() {
        axios.get(burl + '/getcookie')
    },
}

2 个答案:

答案 0 :(得分:1)

@mnesarco所说的是正确的-从技术上来说,您正在运行两个不同的服务器,这意味着您在这两个服务器之间发送的任何请求都是CORS请求。为了在CORS请求中共享发送Cookie,您需要将withCredentials标志设置为true:

export default {
    login : function(email:string, password:string) {
        axios.get(burl + '/setcookie', { withCredentials: true })
    },
    isAuth : function() {
        axios.get(burl + '/getcookie', { withCredentials: true })
    },
}

有关类似情况,请参见this answer,或参见this mdn page

答案 1 :(得分:0)

每个host:port组合是一个不同的站点。您不能在两个不同的“域”之间共享可可块。

相关问题