我正在尝试做什么
我想从React前端向我的API发送PATCH请求。 API使用Identity Server 4来验证请求。
发生了什么
请求有效并从POSTMAN通过控制器,但它不是来自我的前端。当它来自axios请求时,它会抛出一个未经授权的响应。
另外请注意,get请求在前端工作得很好。 get方法也受Identity Server保护
邮差要求
http://localhost:90909/api/products/3434
Headers = {
Authorization: Bearer <token>
Content-Type: application/json-patch+json
}
Body:
[
{
"op" : "replace",
"path" : "/DESCRIPTION",
"value" : "bruhhh"
}
]
反应
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设置
services.AddCors(options =>
{
options.AddPolicy("JSClient", builder =>
builder.WithOrigins("http://localhost:9999")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
日志
我启用了一些日志。以下是我已经posted from a few days ago
的一些内容以下是我从现在开始的内容
预检
在CORS的飞行前检查期间似乎发生以下错误。
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
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响应
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
:
{,…}
答案 0 :(得分:0)
获取请求的服务器需要启用访问权限。
例如,在apache服务器上,在配置文件中添加Header set Access-Control-Allow- Origin :
<Directory />
Header set Access-Control-Allow-Origin "http://ipaddress:[port]"
</Directory>
来源的位置是...... [...]提供反应的地方
邮差很可能被配置为允许任何来源访问......