This Set-Cookie header does not specify the "SameSite" attribute, defaults to "SameSite=Lax", and is blocked because it comes from cross-site responses, not responses to top-level navigation. SetCookie must be set to "SameSite=None" to enable cross-site use.
以上报错为浏览器(google)不支持非https服务设置Set-cookie
解决一、使用https
解决二、在服务端将SameSite = None和secure=true(完整代码在最后)
has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
fetch请求 credentials: 'include' 服务端代码没有做适配(解决查看下列完整代码)
服务端express代码
const cors = require('cors');
app.use(cors()); // cors解决跨域
app.get('/setCookie', (req,res) => {
const userId = '123456789';
// 将 SameSite=None 和 secure=true
res.cookie('user_id', userId, { sameSite: 'none', secure: true });
// 设置后的响应请求头 Set-Cookie: user_id=123456789; Path=/; Secure; SameSite=None
res.send('setCookie');
})
app.post('/getHeaderCookie', (req,res) => {
// 适配前端 credentials: 'include' 携带请求头 cookie 允许的前端地址
res.setHeader('Access-Control-Allow-Origin', 'http:/127.0.0.1:18000');
res.setHeader('Access-Control-Allow-Credentials', 'true');
// 获取请求头cookie数据
console.log(req.headers.cookie);
res.send('getList');
})
前端fetch发动请求代码
// 设置cookie 常用于登录接口
fetch('http://127.0.0.1/setCookie', {
method: 'GET',
}).then((res) => {
console.log(res, 'res')
})
fetch('http://127.0.0.1/getHeaderCookie', {
method: 'POST',
credentials: 'include', // 携带 Cookie
// headers: {
// 'Token': 'SESSION=MGZ', // 手动添加header值
// },
body: JSON.stringify({
encryptParams:'', // post请求参数
}),
}).then((res) => {
console.log(res, 'res')
})
在axios中携带cookie
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // 环境变量base接口地址 url = base url + request url
withCredentials: true, // 跨域请求时发送Cookie
timeout: 60000, // 请求超时
headers: {
"Content-Type": "application/json; charset=UTF-8;"
}
});