繁体   English   中英

Nodejs - Axios 不使用 Cookie 进行发布请求

[英]Nodejs - Axios not using Cookie for post request

我正在为 AXIOS 苦苦挣扎:看来我的帖子请求没有使用我的 Cookie。

首先,我正在创建一个 Axios 实例,如下所示:

const api = axios.create({
    baseURL: 'http://mylocalserver:myport/api/',
    header: {
        'Content-type' : 'application/json',
    },
    withCredentials: true,
    responseType: 'json'
});

我试图与之交互的 API 需要密码,因此我定义了一个包含我的密码的变量:

const password = 'mybeautifulpassword';

首先,我需要发布一个创建会话的请求,并获取 cookie:

const createSession = async() => {
    const response = await api.post('session', { password: password});
    return response.headers['set-cookie'];
}

现在,通过使用返回的 cookie(存储在 cookieAuth 变量中),我可以与 API 交互。

我知道有一个端点允许我检索信息:

const readInfo = async(cookieAuth) => {
    return await api.get('endpoint/a', {
        headers: {
            Cookie: cookieAuth,
        }
    })
}

这工作正常。

当我想发起发布请求时,这是另一回事。

const createInfo = async(cookieAuth, infoName) => {
    try {
        const data = JSON.stringify({
            name: infoName
        })
        return await api.post('endpoint/a', {
            headers: {
                Cookie: cookieAuth,
            },
            data: data,
        })
    } catch (error) {
        console.log(error);
    }
    
};

当我启动 createInfo 方法时,我得到了 401 状态(未授权)。 看起来 Axios 没有将我的 cookieAuth 用于发布请求...

如果我使用 Postman 发出相同的请求,它会起作用...

我在这段代码中做错了什么? 非常感谢你的帮助

我终于发现了我的错误。

正如 Axios Doc ( https://axios-http.com/docs/instance ) 中所写

指定的配置将与实例配置合并。

创建实例后,我必须遵循以下结构来执行发布请求:

axios#post(url[, data[, config]])

我的要求现在有效:

await api.post('endpoint/a', {data: data}, {
            headers: {
                'Cookie': cookiesAuth
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM