我正在尝试从Angular 1.5迁移到Angular 2.4。
我对后端有疑问。是否可以将我的Angular 1应用程序的后端用于我的Angular 2应用程序,而后端没有任何变化?
如果答案是肯定的,为什么我在尝试登录Angular2上的应用程序时遇到此错误net::ERR_SSL_PROTOCOL_ERROR
?
Angular 2代码:
login(loginData: User): Observable<User> {
let data = 'grant_type=password&username=' + encodeURIComponent(loginData.username) + "&password=" + encodeURIComponent(loginData.password);
return this.http.post(`${this.authUrl}` + 'token', data)
.map(res => res.json())
.do(res => {
if (res.token) {
localStorage.setItem('authorizationData', res.token);
this.loggedIn = true;
}
})
.catch(this.handleError);
}
Angular 1代码:
function (loginData) {
var data = "grant_type=password&username=" + encodeURIComponent(loginData.userName) + "&password=" + encodeURIComponent(loginData.password);
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
答案 0 :(得分:2)
您确定要对相同的网址进行HTTP发布吗? (即serviceBase
和this.authUrl + 'token'
包含相同的值?
为什么不在Angular 2代码中设置Content-Type
?
以下是您可以这样做的方法:
let headers: Headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options: RequestOptionsArgs = { headers: headers };
// ...
return this.http.post(`${this.authUrl}token`, data, options); // `options` has appeared
旁注:不要这样做:
`${this.authUrl}` + 'token'
模板文字(反引号)的要点是避免连接(+
符号)。
相反,你应该这样写:
`${this.authUrl}token`
或那:
this.authUrl + 'token'
但不是两者的结合。 :)