【问题标题】:Ajax Header value is return null. but postman show header value in below code how to get header value "Authorization"Ajax 标头值返回 null。但是邮递员在下面的代码中显示标题值如何获取标题值“授权”
【发布时间】:2021-08-19 10:32:53
【问题描述】:

对于后端,我使用的是 Laravel 8,前端响应标头“授权”值中的代码下方返回“空”值,但在邮递员中显示标头部分中的值。

$("#but_submit").click(function(){
                var username = $("#txt_uname").val().trim();
                var password = $("#txt_pwd").val().trim();
             
                if( username != "" && password != "" ){
                    $.ajax({
                        url:'https://localhost:8000/api/login',
                        method:'GET',
                        async:true,
                        crossDomain:true,
                        data:{username:username,password:password},
                        headers: { 'Content-Type':'application/json;charset=utf-8','accept':'application/json'},
                        success:function(response,textstatus,header){
                            console.log(header.getResponseHeader('Authorization'));
                            
                        },error: function(xhr, status, err) {
                        console.error(url_link, status, err.toString());
}
                    });
                }
            });

【问题讨论】:

  • 在 Postman VS Ajax 上的调用方式肯定有所不同。例如,您确定方法是 GET 吗?通常 POST 更常见于身份验证。如果不是这种情况,请尝试调试,在成功函数中使用console.log(response);console.log(header);
  • @AndreaOlivato 是的,我正在使用 Get 方法
  • @AndreaOlivato 当我使用 POST 方法时显示错误 401(未经授权)。

标签: javascript php ajax laravel api


【解决方案1】:

问题解决了。由于跨域资源共享 (CORS),我收到了一个错误。

第 1 步:运行作曲家

composer remove barryvdh/laravel-cors fruitcake/laravel-cors
composer require fruitcake/laravel-cors

Setp 2:在路径中添加中间件

app/Http/Kernel.php

\Fruitcake\Cors\HandleCors::class,

第 3 步:发布供应商

php artisan vendor:publish --tag="cors"

第四步:修改Config/core.php

'exposed_headers' => ['Authorization','Content-Type','accept'],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多