我正在尝试非常简单的角度4 http请求.当我检查chrome开发人员工具时,我看不到http标头.
const headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer: 123213');
this.http.post('https://127.0.0.1:502', JSON.stringify(token), {headers: headers}).subscribe();
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
Max*_*kyi 24
与启动angular@5.x.
该@angular/http
模块已被弃用其所有的类.现在angular/common/http
应该使用.在这里阅读更多.
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
httpOptions
).subscribe();
Run Code Online (Sandbox Code Playgroud)
对于旧版本,您可以这样做:
import {Http, Headers, RequestOptions} from '@angular/http';
export class AppComponent {
constructor(private http: Http) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `hello`);
const options = new RequestOptions({headers: headers});
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
options
).subscribe();
Run Code Online (Sandbox Code Playgroud)
您必须确保从以下位置导入正确的对象@angular/http
:
import {Http, Headers, RequestOptions} from '@angular/http';
Run Code Online (Sandbox Code Playgroud)
如果您仍然没有看到标题,那么您使用的服务器也可能不允许它们.当浏览器向另一个源发出请求时,它会发送access-control-headers-request标头以检查服务器是否允许自定义标头.如果您的服务器未配置为允许自定义标头,则不会在后续请求中看到它们.
Иго*_*нюк 19
如果您使用HttpClient而不是Http,您的代码应如下所示:
login(credintials: Authenticate): Observable<any> {
const body = {
username: credintials.username,
password: credintials.password,
grant_type: 'password',
client_id: credintials.client_id
};
const headers = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Authorization', 'Basic loremlorem');
return this.http.post(`${baseUrl}/uaa/oauth/token`,
body,
{
headers: headers
}
);
}
Run Code Online (Sandbox Code Playgroud)
如果您的参数是可选的,您应该添加这样的参数:
let params: HttpParams = new HttpParams();
if (param) {
params = params.append( 'page', param.page );
}
Run Code Online (Sandbox Code Playgroud)
源代码如下:
/**
* Construct a new body with an appended value for the given parameter name.
*/
append(param: string, value: string): HttpParams;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57375 次 |
最近记录: |