目录
- 跨域请求能够设置Cookie
- Node.js中使用Express框架
- 浏览器中使用Fetch API
跨域请求能够设置Cookie
当你使用CORS(跨源资源共享)时,如果你希望跨域请求能够设置Cookie,需要满足以下几个条件:
- 服务器端需要在响应头中设置Access-Control-Allow-Credentials为true。这表示服务器允许客户端在跨域请求中携带凭证(包括Cookies和HTTP认证信息)。
Node.js中使用Express框架
例如,如果你在Node.js中使用Express框架,可以这样设置:
app.use(function(req, res, next) {
res.header(\’Access-Control-Allow-Credentials\’, true);
next();
});
- 客户端发起请求时,也需要设置withCredentials为true。这表示客户端在发起跨域请求时会携带凭证。
浏览器中使用Fetch API
例如,如果你在浏览器中使用Fetch API,可以这样设置:
fetch(url, {
credentials: \’include\’
});
- 另外,当Access-Control-Allow-Credentials设置为true时,服务器端不能将Access-Control-Allow-Origin设置为*,必须指定具体的域名。例如:
app.use(function(req, res, next) {
res.header(\’Access-Control-Allow-Origin\’, \’http://example.com\’);
res.header(\’Access-Control-Allow-Credentials\’, true);
next();
});
以上就是使用CORS来允许设置Cookie的方法详细内容,更多关于CORS来允许设置Cookie的资料请关注悠久资源其它相关文章!