【问题标题】:Node API on Heroku sends set-cookie headers, but Chrome won't set them (Postman, however, will)Heroku 上的 Node API 发送 set-cookie 标头,但 Chrome 不会设置它们(但是 Postman 会)
【发布时间】:2017-09-24 11:43:28
【问题描述】:

我制作了一个完全剥离的测试 API 和前端来演示这个问题,这将在至少将 API 部署到 Heroku 时发生:

这是整个 API。 app.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}`)
})

package.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:

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

【问题讨论】:

  • 你能解决这个问题吗?

标签: node.js express heroku cookies


【解决方案1】:

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

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

【讨论】:

  • 然而,在开发中,以及在 Postman 中,这种行为是自动的 - Chrome 确实在开发过程中使用 localhost fe 和 api(不同的端口)根据标头自动设置 cookie。
猜你喜欢
  • 2022-08-23
  • 1970-01-01
  • 2015-09-12
  • 2014-02-18
  • 2017-07-01
  • 1970-01-01
  • 2022-07-27
  • 2018-08-10
  • 1970-01-01
相关资源
最近更新 更多