gpt4 book ai didi

node.js - 即使使用 `credentials: ' 也无法使用 cookie 获取包含'`

转载 作者:行者123 更新时间:2023-12-04 15:11:51 25 4
gpt4 key购买 nike

我无法获取发送 cookie。我read对于跨域请求,您必须使用 credentials: 'include' .但这仍然没有给我 cookies 。
获取 html 文档

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>fetch on load</div>
<script>
fetch('http://localhost:4001/sayhi', { credentials: 'include' })
.then((res) => {
return res.text();
})
.then((text) => {
console.log('fetched: ' + text);
})
.catch(console.log);
</script>
</body>
</html>

服务器文件:
const express = require('express');
const mongoose = require('mongoose');

const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

const app = express();
const cors = require('cors');

app.use(cors());
app.use((req, res, next) => {
console.log(req.path);

// this will log a cookie when several
// requests are sent through the browser
// but 'undefined' through `fetch`
console.log('cookie in header: ', req.headers.cookie);

next();
});

app.use(
session({
secret: 'very secret 12345',
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);

app.use(async (req, res, next) => {
console.log(`${req.method}: ${req.path}`);
try {
req.session.visits = req.session.visits ? req.session.visits + 1 : 1;
return next();
} catch (err) {
return next(err);
}
});

app.get('/sayhi', (req, res, next) => {
res.send('hey');
});

(async () =>
mongoose.connect('mongodb://localhost/oneSession', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true,
}))()
.then(() => {
console.log(`Connected to MongoDB set user test`);
app.listen(4001).on('listening', () => {
console.log('info', `HTTP server listening on port 4001`);
});
})
.catch((err) => {
console.error(err);
});
运行的中间件 console.log('cookie in header: ', req.headers.cookie);为每个获取请求返回 undefined。
每个获取请求也在创建一个新 session ,我相信是因为没有设置 cookie。
如何让 cookie 与 fetch 一起发送?
更新:部分答案
我认为到目前为止添加这些有帮助:
//instead of app.use(cors());
app.use(
cors({
credentials: true,
origin: 'http://localhost:5501', // your_frontend_domain, it's an example
})
);

app.use((req, res, next) => {
`res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:5501');` // your_frontend_domain, it's an example
next()
});

但是我还有一个问题:
在 devtools 中,我转到“网络”并刷新 html 文件以再次发送请求。在那里我看到了响应头。我可以看到 Set-Cookie header 已发送,但有一个黄色三角形警告。
enter image description here
它说设置 sameSitetrue .
我需要添加 cookie: { sameSite: 'none' }到 session 选项
app.use(
session({
secret: 'very secret 12345',
resave: true,
cookie: { sameSite: 'none' },
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
在我这样做之后,cookie 收到一个新的黄色三角形警告,说我需要在 cookie 上设置另一个选项- secure: true .但这意味着只有通过 HTTPS 发送的请求才有效。但我正在开发中,无法通过 https 发送。

最佳答案

我为你写了一个例子。
您不需要为 sameSite 属性设置“none”。

{
saveUninitialized: false,
resave: false,
secret: 'very secret 12345',
cookie: {
secure: false,
}
}
前端服务器
// server.js
const express = require('express');
const app = express();
app.use(express.static("./public"));
app.listen(5001);
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
fetch('http://localhost:4001/test', {
method: "POST",
credentials: "include"
}).then(response => {
return response.json()
}).then(json => {
alert('Received: ' + JSON.stringify(json));
})
</script>
</body>
</html>
后端服务器
// other-server.js
const express = require('express');
const app = express();
const session = require('express-session')
var sess = {
saveUninitialized: false,
resave: false,
secret: 'very secret 12345',
cookie: {
secure: false,
}
}

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session(sess))
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type")
res.setHeader("Access-Control-Allow-Origin", "http://localhost:5001")
res.setHeader("Access-Control-Allow-Credentials", true)
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH")
next();
})
app.post('/test', (req, res) => {
console.log(req.sessionID);
req.session.a = "hi"
res.json({a: 1})
})

app.listen(4001, () => {
console.log('start');
});

关于node.js - 即使使用 `credentials: ' 也无法使用 cookie 获取包含'`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65083778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com