如何获得axios来维护API调用之间的cookie/会话? [英] How can I get axios to maintain cookies/session between API calls?
本文介绍了如何获得axios来维护API调用之间的cookie/会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法在我的NodeJS
应用程序中的axios
调用之间维持会话状态.这是相关代码:
I'm having trouble maintaining session state between axios
calls in my NodeJS
app. Here is the relevant code:
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
函数,本质上是裸露的以进行故障排除:
My helpers/initialize.js
function, essentially stripped bare to troubleshoot:
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.
The last output is from the API directly.
我想念什么?
推荐答案
解决方案似乎就在我的面前:
Looks like the solution was right in front of my face:
https://github.com/3846masa/axios-cookiejar-support
这篇关于如何获得axios来维护API调用之间的cookie/会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文