【发布时间】:2018-01-07 15:53:57
【问题描述】:
我有一个可通过 jwt 令牌访问的 api。
我有 postman 和 curl (curl -X POST http://localhost/api/login_check -d _username=login -d _password=pass) 的预期结果,但没有 angular。
使用邮递员成功请求标头:
POST /api/login_check
cache-control: no-cache
postman-token: 2b4a6be8-5c3d-4c66-99f9-daa49572d4bf
user-agent: PostmanRuntime/7.1.1
accept: */*
host: localhost
cookie: PHPSESSID=06u39ri0rr2i2sgdkjr451d6tj
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------825758704558259093486061
content-length: 287
这是我的配置:
Angular CLI: 1.5.5
Node: 9.2.0
OS: linux x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.5.5
@angular-devkit/build-optimizer: 0.0.36
@angular-devkit/core: 0.0.22
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.5
@schematics/angular: 0.1.11
@schematics/schematics: 0.0.11
typescript: 2.4.2
webpack: 3.8.1
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const API_URL = 'http://localhost/api';
@Injectable()
export class SecurityService {
constructor(private http: HttpClient) {
}
login(username: string, password: string) {
let url = `${API_URL}/login_check`;
return this.http.post(
url,
{_username: username, _password: password },
).subscribe(
(response) => {
console.log(response);
}
);
}
}
此调用返回 401 错误,无效凭据。我曾尝试添加带有 contentType: 'application/x-www-form-urlencoded' 的标头,但仍然是同样的错误。
我是 Angular 新手,不明白如何进行此身份验证调用。
谢谢
【问题讨论】:
-
您需要一个授权标头:angular.io/guide/http#headers
-
我认为这不是问题,因为该网址不受保护。通过更深入的调试,我发现我的 Api 收到了请求,但找不到凭据。
-
贴出你的后端代码,也许问题出在那儿。
-
授权标头与受保护的 URL 无关。这是您将 AWT 令牌传递给 API 的方式,以便它可以使用它来授权客户端应用程序。我确定 API 正在接收请求,但没有令牌:401 未授权。
-
我可能误解了自己,我尝试访问的网址是登录页面。所以我没有令牌。我应该放一个空的授权标头吗?
标签: angular angular-httpclient