繁体   English   中英

Heroku 上的节点 API 发送 set-cookie 标头,但 Chrome 不会设置它们(但是 Postman 会)

[英]Node API on Heroku sends set-cookie headers, but Chrome won't set them (Postman, however, will)

我做了一个完全精简的测试 API 和前端来演示这个问题,至少在 API 部署到 Heroku 时会发生:

这是整个 API。 应用程序.js:

const express = require('express')
const cors = require('cors')
const app = express()
const router = express.Router()

// This was supposed to help with problems from Heroku's Vegur
// I also tried app.enable('trust proxy') syntax
app.set('trust proxy', true) 

// allow cors
const corsOptions = {
  'origin': true,
  'credentials': true,
}
app.options('*', cors(corsOptions))
app.use(cors(corsOptions))

const port = process.env.PORT || 3000

app.use(router)

router.get('/', function (req, res) {
  res.send('test ready')
})

router.post('/', function (req, res) {
  res.cookie("testCookie", {
      led: "zepplin",
      pink: "floyd",
    }, {
      encode: String
    })
  res.send("cookie set")
})

app.listen(port, () => {
  console.log(`listening on port ${port}`)
})

包.json:

{
  "name": "testapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js",
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.3",
    "express": "^4.15.2"
  }
}

这是整个前端。 一个 php 单行使其运行,index.php:

<?php header( 'Location: /index.html' ) ;  ?>

和 index.html:

<!DOCTYPE html>
<html>
  <head>
    <script>

      function fetchAPI() {
        fetch(your_heroku_api_url, {
          method: 'POST',
          credentials: 'include',
        })
        .then((response) => {
          return response.text()
        })
        .then((text) => {
          console.log({res: text})
        })
        .catch((er) => {
          console.log({error: er})
        })
      }

    </script>
  </head>
  <body>
    <button onclick=fetchAPI()>FETCH REQUEST</button>
  </body>
</html>

如果我使用 Postman 访问该 POST 路由,我就会得到预期的行为。 将设置 cookie。 如果我从 Chrome 这样做。 我不。 我确实得到了 set-cookie 标头,但 Chrome 不会设置该 cookie:

chrome 开发工具网络选项卡

所以我很困。 我在遇到相同问题的更复杂的应用程序中实现了与此类似的身份验证令牌。 它只是像上面那样使用了Express的res.cookie()方法,它同样到达了浏览器,它也会被忽略。 此外,我还使用client-sessions设置了我的会话。 这些 cookie 表现出相同的不成功行为。 有时,我什至会看到请求中发送的 cookie,但我不知道这是怎么发生的,因为它从未在浏览器中设置过。 同样,当在单独的端口上本地运行时,或者如果 Postman 访问本地或 Heroku API,一切都会正常工作。

不幸的是,ajax 调用中的响应不会影响浏览器中的 cookie。

如果要更改浏览器的 cookie,需要从响应中提取 header 并将其设置为浏览器 cookie。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM