如何让 axios 在 API 调用之间维护 cookie/会话?

Rai*_*l24 5 cookies session node.js express axios

axios我在维护应用程序调用之间的会话状态时遇到问题NodeJS。这是相关代码:

const express = require("express")
const cors = require("cors")
const app = express()
const initialize = require("@helpers/initialize")
const { PORT } = require("@config")

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
})

app.use(cors({
    origin: ['http://localhost:3001'],
    methods: ['GET', 'POST'],
    credentials: true
}))

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

initialize()
Run Code Online (Sandbox Code Playgroud)

我的helpers/initialize.js功能基本上被剥离以进行故障排除:

const axios = require("axios")
const {
    CS_API,
    CS_COMMANDS: { LOGIN }
} = require("@config")

module.exports = () => {
    const loginURL = 'https://api.myhost.com/api/login'
    const getURL = 'https://api.myhost.com/api/active-jobs'
    const username = 'testusername'
    const password = 'testpassword'
    axios.defaults.withCredentials = true
    axios
        .post(loginURL, { username, password }, { withCredentials: true })
        .then(res => {
            if (res.status === 200) {
                console.log('Successfully logged in.')
                axios
                    .get(getURL, { withCredentials: true })
                    .then(res => {
                        console.log('Successfully maintained session state!')
                        console.log(res)
                    })
                    .catch(error => {
                        console.log('Failed to maintain session state!')
                        console.log(error.response.data)
                    })
            }
        })
        .catch(error => console.log(error))
}
Run Code Online (Sandbox Code Playgroud)

收到的输出是:

> App listening on port 3001!
Successfully logged in.
Failed to maintain session state!
Device not logged in.
Run Code Online (Sandbox Code Playgroud)

最后的输出直接来自 API。

我缺少什么?

Rai*_*l24 4

看起来解决方案就在我面前:

https://github.com/3846masa/axios-cookiejar-support