首页 > 解决方案 > 授权问题:Axios POST 中的 Bearer access_token(标头)反应

问题描述

我正在尝试从使用授权和承载 access_token 的端点创建登录。我不知道将令牌正确传递给标头中的授权,因此会发生以下错误。

响应 {type: "basic", url: " http://127.0.0.1:8000/ ", 重定向: true, status: 200, ok: true, ...}

我试图阅读 Axios 帖子和授权类型,以了解如何将 access_token 传递给承载。问题是令牌是在每个用户注册期间生成的。如何在登录中使用它。图片来自邮递员来说明。我将注册时生成的 access_token 复制到授权中。

在此处输入图像描述

handleLogin(event){
      event.preventDefault();
        var formData = new FormData();
        formData.append("password", this.state.l_password);
        formData.append("email",this.state.l_email);
        formData.append("remember_me", true);
      fetch('api/auth/login',
         {
            headers:{
               // 'accept': 'application/x-www-form-urlencoded',
                'content-type': 'application/json',
                'authorization': 'bearer',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            method: "POST",
            body:formData

         }
      )
           .then(response => {
                console.log(response);

            })
            .then(json => {
                return json.json();

            })
        }

在 Postman 中,我只使用 content-type: application/json 作为登录头。但最令人困惑的是,它显示状态:好的,它实际上并没有工作。

在此处输入图像描述

标签: reactjslaravelfetch

解决方案


你做的有点不对。首先,您必须考虑 API 使用需要在端点中指定的令牌,例如/oauth/token。首先,如果您有邮递员,请尝试测试http://localhost:port/oauth/token然后指定标头 content-type:application/json 并在您的正文中执行以下操作:-

{
    "username": "something@yahoo.com", 
    "password" : "abcdef",
    "client_id": "4",
    "client_secret" :"XXXXXXXXXXXXXXXXXXXXXX", 
    "grant_type": "password",
    "scope": "*"
}

如果您仔细查看下面的代码,您可以看到我将所有内容都放入了正文中。

但是,我已经重写了您的代码

handleLogin(event){
      event.preventDefault();
      fetch('/oauth/token',
         {
            method: "POST",
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            },

            body:`grant_type=password&username=${this.state.username}&password=${this.state.l_password}&client_id=4&client_secret=XXXXXXXXXXXXXXXXXXX&scope=*`

         }
      )
      .then(response =>
        response.json()
      )
      .then(responseJson => {
          const returnObj = responseJson;
          console.log(returnObj);
      })

要阅读更多信息,请在此处输入链接描述, 其他资源请在此处输入链接描述


推荐阅读