gpt4 book ai didi

node.js - 如何让 axios 维护 API 调用之间的 cookie/ session ?

转载 作者:行者123 更新时间:2023-12-04 14:19:16 25 4
gpt4 key购买 nike

我在 axios 之间维护 session 状态时遇到问题调用我的 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()

我的 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。

我错过了什么?

最佳答案

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

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

关于node.js - 如何让 axios 维护 API 调用之间的 cookie/ session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com