首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >.Net核心API上的CORS返回来自axios请求的401未经授权的

.Net核心API上的CORS返回来自axios请求的401未经授权的
EN

Stack Overflow用户
提问于 2017-11-15 04:35:04
回答 1查看 1.9K关注 0票数 1

我想做什么,

我想从一个React前端向我的API发送一个补丁请求。API使用Identity Server 4验证请求。

发生了什么

请求工作,并通过控制器从邮递员,但它不是来自我的前端。当它来自axios请求时,它抛出一个未经授权的响应。

另外请注意,get请求从前端运行得很好。get方法也受到身份服务器的保护

邮递员请求

代码语言:javascript
运行
复制
http://localhost:90909/api/products/3434

    Headers =  { 
       Authorization: Bearer <token>
       Content-Type: application/json-patch+json
    }

    Body: 
    [
        {
         "op" : "replace",
         "path" : "/DESCRIPTION",
         "value" : "bruhhh"
        }
    ]

反应

代码语言:javascript
运行
复制
 static update(data){
            let config = {
                data : [],
                headers: { 
                    'Authorization' : 'Bearer ' + data.access_token,
                    'Content-Type' : 'application/json-patch+json'           
                }     
            }

            config.data.push(
                    {
                     "op" : "replace",
                     "path" : "/DESCRIPTION",
                     "value" : "you da best"
                    }

            )

            return axios.patch(root + '/api/products/' + data.product.id, config);

    }

CORS设置

代码语言:javascript
运行
复制
services.AddCors(options =>
            {

                options.AddPolicy("JSClient", builder =>
                    builder.WithOrigins("http://localhost:9999")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

日志

我启用了几个日志。这里有一些我已经posted from a few days ago过的

下面是我现在得到的

飞行前

以下错误似乎发生在CORS的飞行前检查中。

代码语言:javascript
运行
复制
System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\My Site Projects\TestProjects\InventoryApi\AnotherLoggingMiddleware.cs:line 43
Exception thrown: 'System.InvalidOperationException' in InventoryApi.dll
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2017-11-15T03:42:56.0180842Z","tags":{"ai.internal.nodeName":"yay-PC","ai.operation.id":"0HL9BRASKOUFU:00000003","ai.application.ver":"1.0.0.0","ai.internal.sdkVersion":"aspnet5c:2.0.0","ai.operation.name":"OPTIONS /api/products/1020","ai.location.ip":"127.0.0.1","ai.cloud.roleInstance":"yay-PC"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"An unhandled exception has occurred while executing the request","severityLevel":"Error","properties":{"{OriginalFormat}":"An unhandled exception has occurred while executing the request","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware","AspNetCoreEnvironment":"Development","Exception":"System.InvalidOperationException: Writing to the response body is invalid for responses with status code 204.\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.HandleNonBodyResponseWrite()\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame.<WriteAsyncAwaited>d__199.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at InventoryApi.Utilities.AnotherLoggingMiddleware.<Invoke>d__3.MoveNext() in F:\\My Site Projects\\TestProjects\\InventoryApi\\AnotherLoggingMiddleware.cs:line 51\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()"}}}}
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request

我检查了浏览器的网络选项卡,得到204,然后在飞行前请求之后,它再次发送请求后立即得到401。

这是204号

代码语言:javascript
运行
复制
General
Request URL:http://localhost:90909/api/products/1020
Request Method:OPTIONS
Status Code:204 No Content
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:PATCH
Access-Control-Allow-Origin:http://localhost:99999
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PATCH
Connection:keep-alive
Host:localhost:90909
Origin:http://localhost:99999
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

--这是飞行前之后请求的401响应

代码语言:javascript
运行
复制
General
Request URL:http://localhost:90909/api/products/1020
Request Method:PATCH
Status Code:401 Unauthorized
Remote Address:[::1]:90909
Referrer Policy:no-referrer-when-downgrade
Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:99999
Content-Length:0
Date:Wed, 15 Nov 2017 04:24:24 GMT
Server:Kestrel
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RjpcTXkgU2l0ZSBQcm9qZWN0c1xUZXN0UHJvamVjdHasdfaseemVudG9yeUFwaVxhcGlccHJvZHVjdHNcMTAyMA==?=
Request Header
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:850
Content-Type:application/json;charset=UTF-8
Host:localhost:90909
Origin:http://localhost:99999
Referer:http://localhost:99999/inventory/products
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Request Payload
{data: [{op: "replace", path: "/DESCRIPTION", value: "you da best"}], headers: {,…}}
data
:
[{op: "replace", path: "/DESCRIPTION", value: "you da best"}]
headers
:
{,…}
EN

回答 1

Stack Overflow用户

发布于 2017-11-15 04:40:35

获得请求的服务器需要启用访问。

例如,在apache服务器上,在配置文件中添加头集Access-Control-Allow-Origin

代码语言:javascript
运行
复制
<Directory />
        Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>

原点在任何反应的地方.

邮递员,很可能,被配置成允许任何来源访问.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47299422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档