无法从fetch()响应访问cookie

问题描述 投票:0回答:2

即使这个问题在SO多次问过,例如:

fetch: Getting cookies from fetch response

Unable to set cookie in browser using request and express modules in NodeJS

这些解决方案都不能帮助我从fetch()响应中获取Cookie

我的设置如下:

客户

export async function registerNewUser(payload) {
    return fetch('https://localhost:8080/register',
        {
            method: 'POST',
            body: JSON.stringify(payload),
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            }
        });
}

...
function handleSubmit(e) {
    e.preventDefault();

    registerNewUser({...values, avatarColor: generateAvatarColor()}).then(response => {
        console.log(response.headers.get('Set-Cookie')); // null
        console.log(response.headers.get('cookie')); //null
        console.log(document.cookie); // empty string
        console.log(response.headers); // empty headers obj
        console.log(response); // response obj
    }).then(() => setValues(initialState))
}

服务器

private setUpMiddleware() {
    this.app.use(cookieParser());
    this.app.use(bodyParser.urlencoded({extended: true}));
    this.app.use(bodyParser.json());
    this.app.use(cors({
        credentials: true,
        origin: 'http://localhost:4200',
        optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
        credentials: true
    }));
    this.app.use(express.static(joinDir('../web/build')));
}
...
this.app.post('/register', (request, response) => {
    const { firstName, lastName, avatarColor, email, password }: User = request.body;
    this.mongoDBClient.addUser({ firstName, lastName, avatarColor, email, password } as User)
        .then(() => {
            const token = CredentialHelper.JWTSign({email}, `${email}-${new Date()}`);
            response.cookie('token', token, {httpOnly: true}).sendStatus(200); // tried also without httpOnly
        })
        .catch(() => response.status(400).send("User already registered."))
})

enter image description here

javascript node.js express cookies setcookie
2个回答
0
投票
JavaScript fetch方法不会发送客户端Cookie,并且会默默地忽略从服务器端Reference link in MDN发送的Cookie,因此您可以使用XMLHttpRequest方法从客户端发送请求。

0
投票
我知道了。解决方案是像这样将凭据设置为'include'
© www.soinside.com 2019 - 2024. All rights reserved.