我可以通过jwt令牌访问api。
我有postman和curl(curl -X POST http://localhost/api/login_check -d _username=login -d _password=pass
)的预期结果,但没有角度。
邮递员成功的标头请求:
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的新手,并且不了解如何进行此身份验证。
由于
答案 0 :(得分:1)
这可能是因为http.post将内容发布为json,但是您的服务器期待x-www-form-urlencoded(这是您使用CURL -d选项所做的)
您需要设置正确的标题
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
你需要设置正确的身体。使用URLSearchParams
您可以手动执行,也可以使用URLSearchParams
let body = new URLSearchParams();
body.set('_username', username);
body.set('_password', password);
this.http.post(this.loginUrl, body.toString(), options)
如果要手动设置正文,请使用
let body = '_username=username&_password=password';
this.http.post(this.loginUrl, body, options)