首页 > 解决方案 > 为什么我在发送 post 请求时收到错误代码 401

问题描述

从以下请求中,我得到状态代码 302 重定向。但我想发送从响应中收到的 cookie,并重定向到下一页。现在我在发送请求时收到状态码 401,我发现这是因为我需要将 cookie 与重定向一起发送,但是在我获取给我重定向的 url 之前我没有得到 cookie . 我怎么做?

async function login (url) {
        let request = await fetch(url, {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
            body: 'username=name&password=pass&submit=login',
        })

        return request

    }

标签: javascriptcookiesrequesthttp-headershttp-post

解决方案


一般来说,正文数据类型必须与 Content-Type 标头匹配。所以在你的情况下你必须使用

body: new URLSearchParams({
     'userName': 'name',
      'password': 'pass',
      'grant_type': 'password'
    }),

推荐阅读