首先,确认服务器是否需要身份验证。如果需要验证,Angular应该发送带有身份验证标头的请求。在控制台中检查出现问题的请求,确保正确设置了标头。例如,如果使用JWT身份验证,则应设置Authorization标头。示例代码如下:
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }) };
this.http.get(url, httpOptions).subscribe( (response: any) => { console.log(response); }, (error: any) => { if (error.status === 401) { console.log('Unauthorized'); } else { console.error(error); } } );
如果身份验证标头已正确设置,但仍然收到401错误,则可能需要更新身份验证令牌或修改请求以更好地匹配服务器预期的格式。