POST与身体不通过Cookies

时间:2016-12-14 12:10:06

标签: javascript reactjs redux axios axios-cookiejar-support

我正在使用axios-cookiejar-support库。

我有一个包含正文的POST,由于某种原因,Cookie没有被注入到请求中。我在这做错了什么:

return axios
    .post(
        urlJoin(
            config.portal.url,
            'Account/Register'),
        {
            UserName: "testing_engine@test.com",
            UserFirstName: "First Name",
            UserLastName: "Last Name",
            Email: "testing_engine@test.com",
            Password: "...",
            ConfirmPassword: "..."
        },
        {
            jar: cookieJar,
            withCredentials: true
        })
    .then(res => callback())
    .catch(err => callback(err))

奇怪的是,如果我对相同的端点执行GET,则会传递Cookie:

return axios
    .get(
        urlJoin(
            config.portal.url,
            'Account/Register'),
        {
            jar: cookieJar,
            withCredentials: true
        })
    .then(res => callback())
    .catch(err => callback(err));

另外,如果我在没有正文的情况下执行POST,它们会被传递:

.post(
    urlJoin(
        config.portal.url,
        `Account/LoginApi?UserName=${config.portal.userName}&Password=${config.portal.password}`),
    null,
    {
        jar: cookieJar,
        withCredentials: true
    })
.then(res => callback())
.catch(err => callback(err))

Cookie Jar的初始化

import axios from 'axios'
import axiosCookieJarSupport from '@3846masa/axios-cookiejar-support'
import tough from 'tough-cookie'
import urlJoin from 'url-join'

const config = require('config');

import { TEST_STATUS_TYPES, TEST_TASK_TYPES } from '../constants/testsConstants'

axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();

1 个答案:

答案 0 :(得分:5)

正如我评论的那样,我怀疑序列化部分。因为当您将数据作为查询字符串传递时,它会按预期工作。所以试试这个

var qs = require('qs');
return axios
    .post(
        urlJoin(
            config.portal.url,
            'Account/Register'),
        qs.stringify({
            UserName: "testing_engine@test.com",
            UserFirstName: "First Name",
            UserLastName: "Last Name",
            Email: "testing_engine@test.com",
            Password: "...",
            ConfirmPassword: "..."
        }),
        {
            jar: cookieJar,
            withCredentials: true
        })
    .then(res => callback())
    .catch(err => callback(err))