【问题标题】:How can I get axios to maintain cookies/session between API calls?如何让 axios 在 API 调用之间维护 cookie/会话?
【发布时间】:2019-11-08 15:19:39
【问题描述】:

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

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()

我的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))
}

收到的输出是:

> App listening on port 3001!
Successfully logged in.
Failed to maintain session state!
Device not logged in.

最后的输出直接来自 API。

我错过了什么?

【问题讨论】:

标签: node.js express session cookies axios


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2011-12-05
    • 2019-05-17
    • 2014-12-08
    相关资源
    最近更新 更多