通过Observables
在Angular 2中调用如下所示的POST请求 let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + currentUser.token);
this.http.post(environment.API_ENDPOINT + 'user/register?name=' + name + '&email=' + email + '&os_version=' + os_version
+ '&os=' + os + '&device_id=' + device_id,
{ headers }).map((response: Response) => response.json());
问题是Python / tornado Server无法识别标题。当我调试标题时,其他信息有" \ n"。
日志
<URL>/user/register?name=cool2&email=cool2@gmail.com&password=qwerty1233456&os_version=xyz&os=xyz&device_id=xyz,
body: b'{\n "method": null,\n
"headers": {\n "Authorization": [\n "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNTc0Y2UzMzI4YjEyZDgyMWEwMmFkMDllIiwiZXhwIjoxNDkyNTc1NzA3fQ.VkHHr15GQWkZqBllX5I3DUuaEPYOmFYOx92qKZfw8Vs"\n ]\n },
\n "body": null,\n "url": null,\n "withCredentials": null,\n "responseType": null\n}'
答案 0 :(得分:0)
您正在使用错误的参数调用http.post()
- 您将它们作为请求正文发送到您的后端 - 第二个参数。参见
您应该这样称呼它:
import { Headers, RequestOptions } from '@angular/http';
const headers = new Headers({ 'Content-Type': 'application/json' });
const options = new RequestOptions({ headers: headers });
const requestBody = { ... }; // any kind of object
this.http.post(url, requestBody, options);
答案 1 :(得分:0)
你在角度服务中写了错误的后api电话。
它应该是http.post(ApiUri, body, options)
是我在service.ts中使用的代码示例
用户service.ts
import { User } from '../models/user';
import { Injectable } from '@angular/core';
import { Http, Jsonp, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Config } from '../index';
import { AuthCookie } from '../services/auth-cookies-handler';
@Injectable()
export class UserService {
constructor(private jsonp: Jsonp, private _http: Http, private _authCookie: AuthCookie) { }
public jsonHeaders(): Headers {
let headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
let userInfo: any = JSON.parse(this._authCookie.getAuth());
if (userInfo && (this._authCookie.getAuth() != '{"user":"GuestUser"}'))
{
headers.append('Authtoken', 'Basic ' + userInfo.authtoken);
}
return headers;
}
saveUser(user: User): Observable<User> {
let options = new RequestOptions({ headers: this.jsonHeaders(), method: 'post' });
let body = JSON.parse(localStorage.getItem('currentUser')); //--in your case--
//let body = user;
return this._http.post(Config.API + 'users', body, options)
.map((res: Response) => {
return res.json();
})
.catch(this.handleError);
}
}
希望这会对你有所帮助。