由于某些原因,angular没有发送POST请求的Authorization标头
// DOES NOT SEND HTTP HEADERS
let request = this.http.post(root + '/api/lands/favourites', {
headers: new HttpHeaders({
'Authorization': 'Bearer mytoken',
'Accept': 'application/json'
})
});
request.subscribe();
如果我更改HTTP动词,则效果很好
let request = this.http.delete(root + '/api/lands/favourites/'+landId, {
headers: {
'Authorization': 'Bearer myToken',
'Accept': 'application/json'
}
});
request.subscribe();
我可以看到飞行前请求正在运行,但是第二个请求缺少授权标头,因此它无法验证返回401的身份。
我找不到有关角度为什么这样做的任何信息。
CORS飞行前请求:
OPTIONS /api/lands/favourites HTTP/1.1
Host: api.tierras.landium.test.com.ar
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://tierras.landium.test.com.ar
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,es;q=0.9
CORS飞行前响应:
HTTP/1.0 200 OK
Date: Mon, 13 Aug 2018 20:29:06 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.5
X-Powered-By: PHP/7.2.5
Cache-Control: no-cache, private
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://tierras.landium.test.com.ar
Access-Control-Max-Age: 50000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: accept, accept-language, content-language, content-type, authorization, accept-encoding, cache-control, connection, pragma
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8
随后的实际POST请求
POST /api/lands/favourites HTTP/1.1
Host: api.tierras.landium.test.com.ar
Connection: keep-alive
Content-Length: 52
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://tierras.landium.test.com.ar
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Content-Type: application/json
Referer: http://tierras.landium.test.com.ar/land/5
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,es;q=0.9
来自服务器的响应
HTTP/1.1 401 Unauthorized
Date: Mon, 13 Aug 2018 20:29:06 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.5
X-Powered-By: PHP/7.2.5
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 57
Access-Control-Allow-Origin: http://tierras.landium.test.com.ar
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: *
Content-Length: 30
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/json
答案 0 :(得分:5)
如果您发送帖子,我认为您应该在帖子中添加正文。
// DOES NOT SEND HTTP HEADERS
let request = this.http.post(root + '/api/lands/favourites', {BODY}, {
headers: new HttpHeaders({
'Authorization': 'Bearer mytoken',
'Accept': 'application/json'
})
});
request.subscribe();
至少为空{}